Writing a code in matlab for n variables.

  • Thread starter mmmboh
  • Start date
  • #1
407
0
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?
 

Answers and Replies

  • #2
34
1
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])
.
 
  • #3
394
0
return sum(A)/length(A)
 
  • #4
34
1
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).
 
  • #5
394
0
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
 

Related Threads on Writing a code in matlab for n variables.

Replies
10
Views
52K
  • Last Post
Replies
1
Views
3K
Replies
1
Views
4K
  • Last Post
Replies
14
Views
4K
  • Last Post
Replies
7
Views
7K
  • Last Post
Replies
3
Views
2K
Replies
0
Views
2K
  • Last Post
Replies
1
Views
6K
Replies
4
Views
6K
Replies
1
Views
304
Top