Indexing every value from matrix not only unique values

1 回表示 (過去 30 日間)
Bianca Brisc
Bianca Brisc 2021 年 7 月 20 日
コメント済み: Jan 2021 年 7 月 21 日
Hello
For example if I have a matrix like:
A =[ 2 , 2 , 4 , 1 ,3 ;
3 , 1 , 10 , 100]
Is there a posibility to find the index of each value? I tried with find function but it is not working for same values and based on my research I found only solutions either for the same values from the matrix or unique. Not a combination.
Thank you!

採用された回答

Jan
Jan 2021 年 7 月 20 日
Of course you can use find():
A = [2, 2, 4, 1, 3; ...
3, 1, 10, 100, 200]; % 200 added to match number of elements per row...
[i1, i2] = find(A == 2)
i1 = 2×1
1 1
i2 = 2×1
1 2
Now you get the row and column indices of the elements, which are 2.
Do you want to distinguish all elements even if they have the same number? Then this is trivial: Just use the indices.
  8 件のコメント
Bianca Brisc
Bianca Brisc 2021 年 7 月 20 日
Yes! Thank you!
Jan
Jan 2021 年 7 月 21 日
Faster alternatives:
A = [2, 2, 4, 1, 3; ...
3, 1, 10, 100, 200];
S = size(A);
[i1, i2] = ind2sub(S, 1:numel(A))
i1 = 1×10
1 2 1 2 1 2 1 2 1 2
i2 = 1×10
1 1 2 2 3 3 4 4 5 5
% Or:
[S1, S2] = size(A);
Index = [repelem(1:S1, S2); repmat(1:S2, 1, S1)]
Index = 2×10
1 1 1 1 1 2 2 2 2 2 1 2 3 4 5 1 2 3 4 5

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by