フィルターのクリア

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 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