Applying a for loop to every column in a vector

14 ビュー (過去 30 日間)
Louis Meyer
Louis Meyer 2020 年 3 月 5 日
コメント済み: J. Alex Lee 2020 年 3 月 5 日
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 件のコメント
KSSV
KSSV 2020 年 3 月 5 日
Dont use variable name a function name. Rename max with something else.

サインインしてコメントする。

回答 (1 件)

J. Alex Lee
J. Alex Lee 2020 年 3 月 5 日
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 件のコメント
Louis Meyer
Louis Meyer 2020 年 3 月 5 日
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 2020 年 3 月 5 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by