Noaline
Noaline

Reputation: 5

Finding the max element in a column of a matrix excluding certain rows

Consider I have an nxn matrix. My goal is to find the max element of the first column, swap the row containing that largest element and the first row. Next, I want to find the max element of the second column, excluding the first row, then swap the row of this new max element and the second row. Again, finding the max element of the jth column excluding rows 1:j-1, then swapping the max element row with the jth row, up until the n-1th column (as during the nth column, I would only be able to choose from the nth row). My current setup for this is as follows

for j = 1:n-1
   [~,row]=max(A(j:n,j));
   temp = A(row,:);
   A(row,:)=A(j,:);
   A(j,:)=temp;
   ...

While the switching function works well enough, [~, row]=max(A(j:n,j)) is able to, and consistently does for the matrix I'm specifically working on, output row 1 during the second iteration of j. My thought process behind this was that j:n represents the rows we want to check. Noting j=2, for its second iteration, I hoped this would search row 2-to-n; however, it seems to still check every row.

While this question has been asked before, the answer, I found, was this same line of code.

Upvotes: 0

Views: 286

Answers (1)

Daniel
Daniel

Reputation: 36720

You are using [~,row]=max(A(j:n,j));. Let's say you are in iteration j=2. max will only consider the input from the 2nd row on. A return value of row=1 indicates a maximum in the second row of A. The first row you put into the function. The max function has no clue that you actually input something larger. You have to correct for this.

n=5
A=magic(n); %just some input data

for j = 1:n-1
   [~,row]=max(A(j:n,j));
   row=row+j-1;
   temp = A(row,:);
   A(row,:)=A(j,:);
   A(j,:)=temp; 
end

by the way, matlab can do row swapping without helper variable:

for j = 1:n-1
   [~,row]=max(A(j:n,j));
   row=row+j-1;
   A([row,j],:)=A([j,row],:); 
end

Upvotes: 2

Related Questions