フィルターのクリア

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

8 ビュー (過去 30 日間)
N/A
N/A 2011 年 2 月 17 日
回答済み: zeeshan shafiq 2020 年 2 月 4 日
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 Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by