Turn logical matrix into string vector
조회 수: 36 (최근 30일)
이전 댓글 표시
Hi. I have the logical matrix idx and the string array vec.
idx = logical([0 1 0; 0 0 1; 1 0 0; 1 0 0; 0 1 0])
vec = ["A","B","C"]
Each row of idx indicates which letter (from vec) should be assigned to that row.
The desired result is:
result = ["B";"C";"A";"A";"B"]
Is there a way to 'apply' matrix idx to a string matrix, or something like the following:
temp = repmat(vec, [size(idx,1), 1])
temp(idx) %This returns something but not as expected
댓글 수: 0
채택된 답변
Walter Roberson
2021년 5월 1일
편집: Walter Roberson
2021년 5월 1일
idx = logical([0 1 0; 0 0 1; 1 0 0; 1 0 0; 0 1 0])
vec = ["A","B","C"]
vec(idx(:,1)*1 + idx(:,2)*2 + idx(:,3) * 3).'
vec(idx*(1:size(idx,2)).').'
추가 답변 (3개)
Bruno Luong
2021년 5월 1일
편집: Bruno Luong
2021년 5월 1일
Assuming idx has one 1 per row
idx = logical([0 1 0; 0 0 1; 1 0 0; 1 0 0; 0 1 0]);
vec = ["A","B","C"];
[r,c]=find(idx);
result(r)=vec(c)
Yvan Lengwiler
2021년 5월 9일
(I wrote my answer as a comment above. Sorry. Here it is as a formal answer.)
Of course, even if a solution does not appear to use a loop as seen in the Matlab program code, there will be a loop in the ultimapte machine code anyway. Not having a code in the Matlab program can improve legibility of the text for humans, but it is not obvious that it improves the speed of execusion.
Anyway, here is a solution:
idx = logical([0 1 0; 0 0 1; 1 0 0; 1 0 0; 0 1 0]);
vec = ["A","B","C"];
tempvec = repmat(vec', [size(idx',2), 1]);
tempidx = idx'; tempidx = tempidx(:);
result = tempvec(tempidx)'
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Identification에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!