How can I do matrix indexing
조회 수: 3 (최근 30일)
이전 댓글 표시
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
채택된 답변
Stephen23
2019년 2월 8일
편집: Stephen23
2019년 2월 8일
A simple and reliable solution using linear indexing:
>> 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
>> [vec,idx] = max(f,[],1); % value and row index of max in each column.
>> S = size(f); % size of input array.
>> idx = idx + S(1)*(0:S(2)-1); % convert row index into linear index.
>> out = C(idx) % use linear index to get elements of C.
out =
84.367 25.973 31.537
>> vec
vec =
4 33 333
추가 답변 (3개)
madhan ravi
2019년 2월 8일
C(any(f(:)==max(f),2)).'
댓글 수: 13
Stephen23
2019년 2월 8일
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..."
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!