How to take mean of each row/column of matrix with while loop

2 ビュー (過去 30 日間)
Muhammad Arshad Mukhtar
Muhammad Arshad Mukhtar 2020 年 2 月 4 日
I want to take mean of each row/column without mean command.
I created this code but its not working, however it was working with For loop. As I changed it to while loop. Its not working.
%%Taking Mean of Each and Column separately without using built-it mean function. You can use While Loop.
A = [0:2:8;2:1:6;9:3:21]
dim = size(A);
mean = zeros(1,dim(2));
j=1;
while j <= dim(2)
i=1;
while i <= dim(1)
mean(j) = mean(j) + A(i,j);
end
mean(j) = mean(j) / dim(1);
end
mean
%%
If I have a matrix like
A = [1 2 3 4; 4 3 2 1; 3 2 1 4]
and want to call each row or column individually, then I want to perform some operation on that individual row elements. i.e I want to add the elements of each row and column and then I want to take mean of those row and column separately. I want to do it with loop function.

採用された回答

J Chen
J Chen 2020 年 2 月 4 日
You need to update i and j (add 1 to them) at the end of each while loop.
  3 件のコメント
J Chen
J Chen 2020 年 2 月 4 日
You need to add i=i+1 at the end of the inner while loop and j=j+1 at the end of the first while loop. It is better to avoid using mean as the variable name since it is the name of a build in function.
Muhammad Arshad Mukhtar
Muhammad Arshad Mukhtar 2020 年 2 月 6 日
Thanks, its working no.
Appreciated!

サインインしてコメントする。

その他の回答 (1 件)

fred  ssemwogerere
fred ssemwogerere 2020 年 2 月 4 日
Hello, this should do nicely;
% If you want to calculate the average for each row:
A=[1 2 3 4;4 3 2 1;3 2 1 4];
m=0;Z=zeros(size(A,1),1);
for k=1:size(A,1)
m=m+1;
Z(m,1)=0;
for t=1:size(A,2)
Z(m,1)=Z(m,1)+A(k,t);
end
Z(m,1)=Z(m,1)/size(A,1);
end
% Getting the average for each column should now be easy

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by