Clear Filters
Clear Filters

How to find maximum without using max

1 view (last 30 days)
James Crowe
James Crowe on 8 Dec 2017
Answered: KL on 8 Dec 2017
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!

Answers (1)

KL
KL on 8 Dec 2017
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!