Clear Filters
Clear Filters

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

3 views (last 30 days)
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.

Answers (2)

Matt Tearle
Matt Tearle on 17 Feb 2011
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 Comments
Matt Tearle
Matt Tearle on 17 Feb 2011
or, failing that, just modify what you already have for the sum, and divide the final answer by (row*col)
Paulo Silva
Paulo Silva on 17 Feb 2011
I was going to post this outsum/numel(mat) but Matt was faster :( (numel(mat)=row*col)

Sign in to comment.


zeeshan shafiq
zeeshan shafiq on 4 Feb 2020
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

Community Treasure Hunt

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

Start Hunting!