To find maximum value of any matrix without using built-in max()
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Kae-Shyang Chen
el 5 de Sept. de 2018
Comentada: Kae-Shyang Chen
el 5 de Sept. de 2018
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
0 comentarios
Respuesta aceptada
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
Stephen23
el 5 de Sept. de 2018
@Kae-Shyang Chen: you will need to know about linear indexing:
Más respuestas (2)
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?
Ver también
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!