Create a function to find the average of an entire matrix only using loops

3 次查看(过去 30 天)
I need to create a function only using loops (preferably only the for loop) to find the average of an inputted matrix. I am a novice at MATLAB so I really need help with this. So far, I can get the sum of the matrix using this:
function outsum = mymatsum(mat)
[row col] = size(mat);
outsum = 0;
for i = 1:row
for j = 1:col
outsum = outsum + mat(i,j);
end
end
I need to be able to use something similar to get the average of the entire matrix. It needs to be a single number, not an array.

回答(2 个)

Matt Tearle
Matt Tearle 2011-2-17
Why the requirement for a loop? The neatest way to do this is:
mean(x(:))
But if you really want a loop,
function y = matrixmean(x)
n = numel(x);
tot = 0;
for k=1:n
tot = tot + x(k);
end
y = tot/n;
Note the use of a "linear index" for the matrix (ie one index value instead of two).
  2 个评论
Matt Tearle
Matt Tearle 2011-2-17
or, failing that, just modify what you already have for the sum, and divide the final answer by (row*col)
Paulo Silva
Paulo Silva 2011-2-17
I was going to post this outsum/numel(mat) but Matt was faster :( (numel(mat)=row*col)

请先登录,再进行评论。


zeeshan shafiq
zeeshan shafiq 2020-2-4
Lets try like this
% x=[1 4 5 7 8 9 3];
% N=[3 4 12 34 54 56 6];
clear
clc
function ave=myaverage(x,N)
sizex=size(x);
sizeN=size(N);
if sizex(2)~=sizeN(2)
beep
disp('Error')
else
total= sum(N);
s=x.*N;
ave=sum(s)/total;
end
end

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by