Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

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

1 visualización (últimos 30 días)
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?

Respuestas (1)

Image Analyst
Image Analyst el 29 de Oct. de 2019
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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by