Info
此问题已关闭。 请重新打开它进行编辑或回答。
Trying to find the maximum value in a matrix using for loops? Can someone correct my code?
2 次查看(过去 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?
0 个评论
回答(1 个)
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
0 个评论
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!