Writing a code in matlab for n variables.

AI Thread Summary
The discussion revolves around writing a MATLAB function to calculate the average of n variables. Initially, the user created a function for five variables but sought assistance in generalizing it for any number of inputs. The solution provided involves passing a vector to the function and using a loop to compute the average. Additionally, it is emphasized that MATLAB has a built-in function, mean(x), which is more efficient and optimized for this purpose. The conversation highlights the importance of utilizing built-in functions for better performance in coding.
mmmboh
Messages
401
Reaction score
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?
 
Physics news on Phys.org
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).
 
JeSuisConf said:
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
 

Similar threads

Replies
0
Views
156
Replies
2
Views
2K
Replies
2
Views
2K
Replies
2
Views
218
Replies
6
Views
5K
Replies
1
Views
2K
Replies
7
Views
1K
Back
Top