To find maximum value of any matrix without using built-in max()

3 visualizaciones (últimos 30 días)
function [max_value, index] = mymax(x)
[r,c]=size(x);
max_value_row=x(1,1)
max_value_col=x(1,1)
for i=1:c
if x(1,i)>max_value_row
max_value_row=x(i,1);
end
for k=1:r
if x(k,1)>max_value_col
max_value_col=x(k,1);
end
end
end
if max_value_row > max_value_col
max_value = max_value_row
else
max_value = max_value_col
index = find(max_value)
end
THis is what i have tried so far but the value found is wrong, please help me

Respuesta aceptada

Stephen23
Stephen23 el 5 de Sept. de 2018
Editada: Stephen23 el 5 de Sept. de 2018
function [val,idx] = mymax(arr)
val = arr(1);
idx = 1;
for k = 2:numel(arr)
if arr(k)>val
val = arr(k);
idx = k;
end
end
This return the linear index, which is more useful than the subscript index.
  5 comentarios
Kae-Shyang Chen
Kae-Shyang Chen el 5 de Sept. de 2018
I have a clearer picture on linear indexing now. Thank you so much in helping me!

Iniciar sesión para comentar.

Más respuestas (2)

Guillaume
Guillaume el 5 de Sept. de 2018
Forget about the code for now. What you've written is fundamentally wrong at the algorithmic level for many reasons. You need to spend more time thinking about what the steps of your algorithm should be.
If you can't spot the issues with your code just by reading it, then I suggest you use the debugger to execute your program one line at a time and observe what happens. When you do that, you'll quickly see that your code
  • only look at row 1 and column 1 of tha matrix and ignore all other rows/columns
  • calculate the maximum of the 1st column c times
Questions that should help you come up with a better algorithm:
  • Why do you need to iterate over columns or rows? Can't you just iterate over all the elements just once using linear indexing
  • Wouldn't the maximum calculated by row and the maximum calculated by column be the same?
  1 comentario
Kae-Shyang Chen
Kae-Shyang Chen el 5 de Sept. de 2018
hi, thank you for your guidance.. What i was trying to do is to find the maximum value of the entire matrix instead. I tried the following approach: 1. To find max.value of columns and rows 2. To compare both value and decide the max.value for the entire matrix

Iniciar sesión para comentar.


Kae-Shyang Chen
Kae-Shyang Chen el 5 de Sept. de 2018
I tried this and it works! @Guillaume @Stephen Cobeldick
[r,c]=size(x);
max_value=x(1,1);
for k=1:r
for i=1:c
if x(k,i)>max_value
max_value=x(k,i);
end
end
end

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by