Create an array whose values depend on another array

If I have an array like
C = [1 2 3 4 5 2 4 5 6 7 6 2 5 7 8]
I would like to obtain another array where the value of :
1,4,7 are substitued with 1.
2,5 with 2
3,6,8 with 3
to obtain:
F = [1 2 3 1 2 2 1 2 3 1 3 2 2 1 3]
F should be a numeric vector and not a string or a character.
Which is the fastest and most efficient way?

 採用された回答

KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 7 月 26 日
編集済み: KALYAN ACHARJYA 2019 年 7 月 26 日

0 投票

C=[1 2 3 4 5 2 4 5 6 7 6 2 5 7 8]
F=C;
idx=find(C==1 | C==4 | C==7);
F(idx)=1;
idx=find(C==2 | C==5);
F(idx)=2;
idx=find(C==3 | C==6 | C==8);
F(idx)=3;
F
Commad Window:
C =
1 2 3 4 5 2 4 5 6 7 6 2 5 7 8
F =
1 2 3 4 2 2 4 2 3 1 3 2 2 1 3

5 件のコメント

madhan ravi
madhan ravi 2019 年 7 月 26 日
編集済み: madhan ravi 2019 年 7 月 26 日
You don’t need find() here, use logical indexing.
KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 7 月 26 日
編集済み: KALYAN ACHARJYA 2019 年 7 月 26 日
yes @madhan ravi give me minutes please
This way
C=[1 2 3 4 5 2 4 5 6 7 6 2 5 7 8]
F=C;
F(C==1 | C==4 | C==7)=1
F(C==2 | C==5)=2
F(C==3 | C==6 | C==8)=3
F
right?
Thanks always!
madhan ravi
madhan ravi 2019 年 7 月 26 日
編集済み: madhan ravi 2019 年 7 月 26 日
(C==1 | C==4 | C==7) * 1 + (C==2 | C==5) * 2 +...
(C==3 | C==6 | C==8) * 3
KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 7 月 26 日
編集済み: KALYAN ACHARJYA 2019 年 7 月 26 日
Great! @Madhan
luca
luca 2019 年 7 月 26 日
THANKS

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品

リリース

R2019a

質問済み:

2019 年 7 月 26 日

コメント済み:

2019 年 7 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by