# Writing a code in matlab for n variables.

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)
av=(x1+x2+x3+x4+x5)/5;
return;"
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?

The way this is normally done is to pass x as a vector. So your function looks roughly like this:
Code:
function av = average(x)
[INDENT]n = length(x);
av=0;
for i=1:n
[INDENT]av=av+x(i)/n;[/INDENT]
end[/INDENT]
end

To call that function you use a vector. E.g.
Code:
average([1 3 5 9])
.

return sum(A)/length(A)

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).

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).

hahaha! that's awesome. so this guy has an assignment to write code that a built in matlab function already does.

edit:
here is the built in mean() code:

Code:
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);
else
y = sum(x,dim)/size(x,dim);
end