1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Writing a code in matlab for n variables.

  1. Sep 12, 2010 #1
    Hi, I am very new to matlab, this is actually the first time I am using it. I have to write a code for finding averages, right now I have "function av=average(x1,x2,x3,x4,x5)
    % average(x1,x2,x3,x4,x5) returns the average of (x1,x2,x3,x4,x5)
    This works just fine when there are 5 things to average, but I can't figure out how to make it work for n variables. Can someone help me please?
  2. jcsd
  3. Sep 14, 2010 #2
    The way this is normally done is to pass x as a vector. So your function looks roughly like this:
    Code (Text):

    function av = average(x)
    [INDENT]n = length(x);
    for i=1:n
    To call that function you use a vector. E.g.
    Code (Text):
    average([1 3 5 9])
  4. Sep 14, 2010 #3
    return sum(A)/length(A)
  5. Sep 14, 2010 #4
    Yeah, in practice you want to always do it as xcvxcvvc suggests - always use the built in functions when possible, because they are usually memory optimized and sometimes numerically optimized. Even better, MATLAB has a function to compute the mean: mean(x).
  6. Sep 14, 2010 #5
    hahaha! that's awesome. so this guy has an assignment to write code that a built in matlab function already does.

    here is the built in mean() code:

    Code (Text):

    if nargin==1,
      % Determine which dimension SUM will use
      dim = min(find(size(x)~=1));
      if isempty(dim), dim = 1; end

      y = sum(x)/size(x,dim);
      y = sum(x,dim)/size(x,dim);
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook