필터 지우기
필터 지우기

How to find maximum without using max

조회 수: 1 (최근 30일)
James Crowe
James Crowe 2017년 12월 8일
답변: KL 2017년 12월 8일
The question is:
Write a function to calculate the maximum row sum of a matrix A. The function should have as input a matrix A and should give as outputs the maximum row sum of A and the row on which that maximum occurs, you should use loops to do the calculation and not use in-built functions such as sum, norm, max or min etc.
What I have done so far is:
function [MaxRowSum, RowOccured] = myFunction(A)
a = size(A,1);
for i = 1:a
m(i) = A(i,1)+A(i,2)+A(i,3);
end
How would I make this work for any number of columns, ie A(1,1)...+A(1,n)? How would I find the maximum sum without using max? Thank you!
  댓글 수: 1
James Crowe
James Crowe 2017년 12월 8일
How would I do that last loop? and thank you

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

답변 (1개)

KL
KL 2017년 12월 8일
You would need to use two for loops. One to move across rows, the other to move across the elements in each row (columns). What you have done so far helps you with the rows but you'd need another loop inside the existing loop to achieve the latter.
function [MaxRowSum, RowOccured] = myFunction(A)
[row, column] = size(A);
%pre-allcate a result matrix of approriate size
A_row_sum = zeros(?,?);
for r = 1:row
for c = 1:column
%create sum for one row here, iterative process. You only get the sum if all iterations are completed
end
%store the calculated sum in the A_row_sum variable here
end
Now that you'll have all the sum in the new variable. You can either create a new loop to find the maximum of those elements using if-else conditions or write it also in the above structure.
Hint: iterate through row sums, use > operator with if else to store the current maximum.

카테고리

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