Calling a indices using 'find' function

1 view (last 30 days)
Ethan Boyce on 5 Sep 2020
Commented: Walter Roberson on 8 Sep 2020
I guess the easiest way to ask this question is to show first,
a = [1 -1 2 -1; 2 -2 3 -3;1 1 1 0; 1 -1 4 3];
[row,col] = find(a==maxk(abs(a(:,3)),1))
Is there then a way to assign say a( __,:) to the row that is returned in this function? For example, If I want to swap a(1,:) with the row a(__,:) found from this find command, how would I go about it?

Walter Roberson on 5 Sep 2020
a==maxk(abs(a(:,3)),1)
If you know for sure that a(:,3) is always positive, then the abs() is not needed.
If you do not know for sure that a(:,3) is always positive, then it is possible that the element with largest absolute value is a negative element, in which case there might not be any locations in a that equal the absolute value of that negative element -- row and col might be empty, in which case it makes not sense to swap.
If you know for sure that there will be exactly one entry in a equal to the entry in a(:,3) with maximal absolute value, then you might as well use a simpler flow with just a max() call, getting out a row index, and knowing that the column index must be 3 for what you locate.
If you do not know for sure that there will be exactly one entry in a equal to the entry in a(:,3) with maximal absolute value then row and col might be be empty or might be vectors; in either case it is not clear what swapping would mean.
It is possible (at least to outside observers) that the maximal absolute value is in row 1, in which case it is not clear what it means to do the swapping.
Anyhow, the answer you are looking for is:
a([1 row], :) = a([row 1], :); %swap rows.
... keeping in mind the reasons I described why your code could fail.

Ethan Boyce on 5 Sep 2020
Understood, thank you. A question about the syntax in your suggestion, what does the input of 1 reference?
Walter Roberson on 8 Sep 2020
The 1 refers to "a(1,:)" that you want to swap with, if you are referring to the swapping code I posted.
If you are referring to the maxk, then then 1 is the number of maximum values to find, and is copied from your code.

Community Treasure Hunt

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

Start Hunting!