A very quick question

2 ビュー (過去 30 日間)
Radoslav Gagov
Radoslav Gagov 2017 年 4 月 12 日
コメント済み: Radoslav Gagov 2017 年 4 月 12 日
Hello Guys. Can you tell me how can I write a code that is like
>> [ida,idb] = ismember('1','1 0 0 1')
ida =
logical
1
idb =
1
but the outpoot i need is
idb =
[1 4]
I suppose it can be made with a double loop or smth, but I am looking for a simpler way.
  2 件のコメント
Stephen23
Stephen23 2017 年 4 月 12 日
編集済み: Stephen23 2017 年 4 月 12 日
@Radoslav Gagov: do the inputs have to be strings ? Or can they be numeric?
Radoslav Gagov
Radoslav Gagov 2017 年 4 月 12 日
Normally they are numeric or logical

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

回答 (2 件)

David J. Mack
David J. Mack 2017 年 4 月 12 日
編集済み: David J. Mack 2017 年 4 月 12 日
Hey Radoslav,
In general, to convert a logical array to ids use find.
If you are working on numbers (as implied in your example) try
idb = find(ismember(1,[1 0 0 1])) % No quotes!
If you work on strings, either use a "set" with a cellstr:
idb = find(ismember('1',{'1','0','0','1'}))
Or better, use strfind without the spaces.
str = '1 0 0 1';
idb = strfind('1',str(~isspace(str))); % Remove spaces
Hope that helps.
Greetings, David

Andrei Bobrov
Andrei Bobrov 2017 年 4 月 12 日
編集済み: Andrei Bobrov 2017 年 4 月 12 日
A = '1 0 0 1';
B = '1';
An = A - '0';
Bn = B - '0';
An = An(An >= 0);
Bn = Bn(Bn >= 0);
idb = find(Bn == An);
for numeric
idb = find(B == A);
  2 件のコメント
Radoslav Gagov
Radoslav Gagov 2017 年 4 月 12 日
Hmm that works thanks. Can you just explain to me why do we make that An = A - '0'. What does this like actually do ?
Radoslav Gagov
Radoslav Gagov 2017 年 4 月 12 日
O yes i found out why. U are transforming the chars in to numbers, but i still dont get it what does - '0' does.

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by