Extracting a vlue from a matrix using a neighboring value as a reference

1 view (last 30 days)
How would I go about extracting an indivdual value from column based on the max value from anothe row?
Say I have the following 2 x 5:
1 2 4 10 3
6 27 30 3 1
And I want to extract a value from Row 2, based on the column of the max value of Row 1. Which in this case would give me 3.

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 25 Nov 2023
If you want the value corresponding to all occurences of the maximum value in row 1 -
%Input data
arr = [1 2 4 10 3 10
6 27 30 3 1 5];
idx1 = arr(1,:) == max(arr(1,:));
val1 = arr(2, idx1)
val1 = 1×2
3 5
If you want the value corresponding to the first occurence of the maximum value in row 1 -
[~, idx2] = max(arr(1, :));
val2 = arr(2, idx2)
val2 = 3
  2 Comments
Alan Jurisich
Alan Jurisich on 25 Nov 2023
Edited: Alan Jurisich on 25 Nov 2023
Hope you don't mind me reapeating it back. I want this to stick.
So i can use ~ to ignore creating a variable for the values, and just create the value for the index. Then max(arr(1, :)) will just search the first row.
Last, using the index variable (idx2) in the column position, MATLAB will just read the column portion of idx2. As in it wont get confused seeing what I assume would be a vector.
or would idx2 just equal the value of the column?
Dyuman Joshi
Dyuman Joshi on 25 Nov 2023
"So i can use ~ to ignore creating a variable for the values, and just create the value for the index."
Correct, it ignores the first output argument from the function.
"Then max(arr(1, :)) will just search the first row."
Correct.
"or would idx2 just equal the value of the column?"
Yes, idx2 is equal to the value of column, where the maximum of row 1 occurs for the 1st time.
%Input data
arr = [1 2 4 10 3 10
6 27 30 3 1 5];
[~, idx2] = max(arr(1, :))
idx2 = 4
10 appears first in the 4th column of row 1.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!