Info

此问题已关闭。 请重新打开它进行编辑或回答。

Trying to find the maximum value in a matrix using for loops? Can someone correct my code?

1 次查看(过去 30 天)
Here is the question:
Find the largest element of the matrix A = [1,2,3; 4,5,6] using for loops.
Here is what I have:
A=[1,2,3;4,5,6]
maxval=A(2)
for ii=3:length(A)
if A(ii)>maxval
maxval=A(ii);
end
end
I am not getting the right answer at all...in fact, Matlab is outputting 2. Help please?

回答(1 个)

Image Analyst
Image Analyst 2019-10-29
length() gives the max length of the longest dimension of an array. So you can either use
A=[1,2,3;4,5,6]
maxval = -inf;
for k = 1 : numel(A)
if A(k) > maxval
maxval=A(k)
end
end
or use two indexes and two loops:
A=[1,2,3;4,5,6]
maxval = -inf;
for row = 1 : size(A, 1)
for column = 1 : size(A, 2)
if A(row, column) > maxval
maxval=A(row, column)
end
end
end

标签

Community Treasure Hunt

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

Start Hunting!

Translated by