How to find maximum without using max
4 次查看(过去 30 天)
显示 更早的评论
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 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!