Turn logical matrix into string vector

65 ビュー (過去 30 日間)
Haris K.
Haris K. 2020 年 10 月 17 日
コメント済み: Yvan Lengwiler 2021 年 5 月 9 日
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

採用された回答

Walter Roberson
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])
idx = 5×3 logical array
0 1 0 0 0 1 1 0 0 1 0 0 0 1 0
vec = ["A","B","C"]
vec = 1×3 string array
"A" "B" "C"
vec(idx(:,1)*1 + idx(:,2)*2 + idx(:,3) * 3).'
ans = 5×1 string array
"B" "C" "A" "A" "B"
vec(idx*(1:size(idx,2)).').'
ans = 5×1 string array
"B" "C" "A" "A" "B"
  1 件のコメント
Haris K.
Haris K. 2021 年 5 月 9 日
Great, thank you!

サインインしてコメントする。

その他の回答 (3 件)

Haris K.
Haris K. 2020 年 10 月 17 日
Btw, here is one solution:
arrayfun(@(i) vec(idx(i,:)),1:size(idx,1))'
But I was wondering if there is something that does not use any for-loop directly or indirectly.

Bruno Luong
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)
result = 1×5 string array
"B" "C" "A" "A" "B"
  1 件のコメント
Haris K.
Haris K. 2021 年 5 月 9 日
Thanks all for your effort!

サインインしてコメントする。


Yvan Lengwiler
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)'
  2 件のコメント
Walter Roberson
Walter Roberson 2021 年 5 月 9 日
Seems over-complicated compared to
vec(idx*(1:size(idx,2)).').'
Yvan Lengwiler
Yvan Lengwiler 2021 年 5 月 9 日
True :-)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by