Find the average of a column without the use of commands.

조회 수: 4 (최근 30일)
Cappi Nguyen
Cappi Nguyen 2023년 5월 15일
편집: Sai 2023년 5월 18일
I have a matrix that is [365,4] and I need to find the average of each column without the use of commands like mean or size. With the use of a for loop.
  댓글 수: 5
Cappi Nguyen
Cappi Nguyen 2023년 5월 15일
Nevermind I am sorry, I realize I could use the size command for this code. But I don't have any errors in the code just needed some help with it.
dpb
dpb 2023년 5월 15일
Beware! length is a dangerous command/function that may not return what you intend -- it is defined as max(size(x)) and so returns either the number of elements in a row or column of any 2D array -- which would depend upon the array configuration. The 4x3 or 3x4 array will both return 4...

댓글을 달려면 로그인하십시오.

답변 (1개)

Sai
Sai 2023년 5월 18일
편집: Sai 2023년 5월 18일
Hi Cappi,
I understand that you wanted to calculate the average of columns of a matrix without the usage of in-built commands.
Please find the following code snippet to do the same.
A = [1 2 3;4 5 6;7 8 9;10 11 12] %Consider the matrix for reference
A = 4×3
1 2 3 4 5 6 7 8 9 10 11 12
nRows = height(A);
nColumns = width(A);
avg = zeros(1,nColumns);
for i = 1:width(A)
C = A(:,i);
sum = 0;
for j = 1:nRows
sum = sum + C(j);
end
avg(i) = sum/nRows;
end
disp(avg)
5.5000 6.5000 7.5000

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by