How can I do matrix indexing
Show older comments
I want to select 3 elements from the matrix C, one element from each column, the selecting will be regarding to the maximum value in in each column in matrix f.
C=
41.0875 66.4048 31.5374
84.3670 25.9733 73.1052
68.8608 99.4798 75.5581
the vector needed like this [ 68.8608 66.4048 73.1052 ]
f=
1.0027 0.9766 1.2106
0.4001 0.5136 1.8174
1.5451 0.9488 0.8571
and because this values and positions are subject to change randomly
any help will be very thankful
1 Comment
KSSV
on 8 Feb 2019
REad about max
Accepted Answer
More Answers (3)
madhan ravi
on 8 Feb 2019
C(any(f(:)==max(f),2)).'
13 Comments
Torsten
on 8 Feb 2019
I get
[84.3670 99.4798 31.5374]
not
[68.8608 66.4048 73.1052]
madhan ravi
on 8 Feb 2019
>> f=[ 1.0027 0.9766 1.2106
0.4001 0.5136 1.8174
1.5451 0.9488 0.8571 ]
C=[41.0875 66.4048 31.5374
84.3670 25.9733 73.1052
68.8608 99.4798 75.5581]
C(any(f(:)==max(f),2)).'
f =
1.0027 0.9766 1.2106
0.4001 0.5136 1.8174
1.5451 0.9488 0.8571
C =
41.0875 66.4048 31.5374
84.3670 25.9733 73.1052
68.8608 99.4798 75.5581
ans =
68.8608 66.4048 73.1052
>>
Torsten
on 8 Feb 2019
Sorry, my mistake.
madhan ravi
on 8 Feb 2019
No problem ;-)
Ashraf Sherif
on 8 Feb 2019
Edited: Ashraf Sherif
on 8 Feb 2019
madhan ravi
on 8 Feb 2019
C(any(bsxfun(@eq,f(:),max(f)),2)).'
Ashraf Sherif
on 8 Feb 2019
madhan ravi
on 8 Feb 2019
Edited: madhan ravi
on 8 Feb 2019
Ashraf Sherif
on 8 Feb 2019
Ashraf Sherif
on 8 Feb 2019
madhan ravi
on 8 Feb 2019
No problem.
Stephen23
on 8 Feb 2019
Note that this is very fragile code, and it can easily fail when values repeat in matrix f:
>> f = [1,22,333;4,33,111;1,4,33]
f =
1 22 333
4 33 111
1 4 33
>> C = [41.0875,66.4048,31.5374;84.3670,25.9733,73.1052;68.8608,99.4798,75.5581]
C =
41.087 66.405 31.537
84.367 25.973 73.105
68.861 99.480 75.558
>> C(any(f(:)==max(f),2)).'
ans =
84.367 25.973 99.480 31.537 75.558 % <- why five output values?
See my answer for code that actually delivers what the question asked for: " I want to select 3 elements from the matrix C, one element from each column..."
madhan ravi
on 8 Feb 2019
Agree with Stephen , @Ashraf accept Stephen's answer.
Ashraf Sherif
on 8 Feb 2019
0 votes
Ashraf Sherif
on 8 Feb 2019
Edited: Ashraf Sherif
on 8 Feb 2019
0 votes
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!