Create a function to find the average of an entire matrix only using loops
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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.
0 Commenti
Risposte (2)
Matt Tearle
il 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 Commenti
Matt Tearle
il 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
il 17 Feb 2011
I was going to post this outsum/numel(mat) but Matt was faster :( (numel(mat)=row*col)
zeeshan shafiq
il 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
0 Commenti
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!