필터 지우기
필터 지우기

avarage of diagonal elements

조회 수: 6 (최근 30일)
Mustafa Ahmed
Mustafa Ahmed 2021년 5월 3일
댓글: Mustafa Ahmed 2021년 5월 3일
Write a Matlab function that calculates the average of the elements of the diagonal of a matrix M.
Be careful, before doing this calculation, your function must check if M is a scalar, a vector or a
matrix. In case it is a scalar or a vector, it must return 0
  댓글 수: 1
Mustafa Ahmed
Mustafa Ahmed 2021년 5월 3일
i did like that ,,,, but it is not enough and did not work
function ave = average(A)
if ismatrix(A)
[r,c] = size(A);
for i=1:r
for j=1:c
b = diag(A)
ave=b./size(A)
end
end
end

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

답변 (1개)

Adam Danz
Adam Danz 2021년 5월 3일
편집: Adam Danz 2021년 5월 3일
Since this appears to be an assignment I can help by explaining what's wrong and nudging you in the right direction.
Two errors in this line:
ave=b./size(A)
1) The size function returns the number of rows in the first output. If A is a square matrix, that's OK but if A is not square, it's very wrong. A is probablly square since you need the diagonal buy why not play it safer by using the number of elements in b instead of the number of rows in A? See numel().
2. That line is computing element-wise division instead of the computing the mean. "./" vs "/"
Also, you don't need any of the loops.
  댓글 수: 3
Adam Danz
Adam Danz 2021년 5월 3일
Like I said, I can point you in the right direction but I won't do it for you.
You don't need the loops. You only need the lines within the loops.
Look at what this line does, look at the output
b = diag(A)
That's what you need to average.
Mustafa Ahmed
Mustafa Ahmed 2021년 5월 3일
thank you

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by