Applying a for loop to every column in a vector

15 vues (au cours des 30 derniers jours)
Louis Meyer
Louis Meyer le 5 Mar 2020
Commenté : J. Alex Lee le 5 Mar 2020
I have some code which tells me the largest value in the first column of a matrix, as well as the index (row) at which it occurs. First, I have noticed these two functions work properly, except when the largest value appears in the first row, causing the outputed index to be incorrect, why might this be? Next, I need to perform this operation (finding the largest value in each column) across each column in the matrix, how can this be done with a loop of some sort? my current code is below
x = randi (10,7,4)
[rows, columns] =size (x);
max = x(1,1);
for i = 1:rows %need to apply this 'for' loop on all columns of x and output a vector of all the results
if x(i,1)>max;
max =x(i,1);
index =i;%index output is incorrect when max is in first row
end
end
index
max
  1 commentaire
KSSV
KSSV le 5 Mar 2020
Dont use variable name a function name. Rename max with something else.

Connectez-vous pour commenter.

Réponses (1)

J. Alex Lee
J. Alex Lee le 5 Mar 2020
Agree with KSSV, avoid naming as "max", but in this case it is not causing your problem.
Your problem is that "index" should not be defined in case the max value is in the first row, because you would never execute the assignment
index = i
Assuming you've run several times without clearing variables, you should have noticed that the incorrect index is in fact the index from the previous time you ran.
  3 commentaires
Louis Meyer
Louis Meyer le 5 Mar 2020
Great, I was able to get around the index problem so it now works properly. Now my only issue is how to apply that operation to every column, such that the output is two vectors, one of the maximum value in each column, and one of the row number (index) in which the maximum value appears in each column. Essentially I need to write my own code to mimick the build in max function. Thanks for your help so far!
J. Alex Lee
J. Alex Lee le 5 Mar 2020
you can "nest" loops. instead of (i,1), think about if you could do (i,j) where j was another index for another loop either inside or outside of your current loop over i.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by