Indexing every value from matrix not only unique values

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!

 Accepted Answer

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 Comments

I understand what you are saying. But I also want the indexes of the unique values in the same row with the indexes of the same values.
I cannot follow you. What is the wanted output for the shown matrix A?
i1 = 1
1
i2 = 1
2
i3 = 1
3
i4 = 1
4
i5 = 1
5
and so on....
I want the index of each element not only the elements with the same value.
The row indices are 1:size(A, 2), the column indices 1:size(A, 1). You can either use two loops or it might be easier to use the "linear index", which is counted from 1:numel(A).
A = [2, 2, 4, 1, 3; ...
3, 1, 10, 100, 200];
for i1 = 1:size(A, 1)
for i2 = 1:size(A, 2)
A(i1, i2)
end
end
% Or the linear index (going in column order):
for k = 1:numel(A)
A(k)
end
In this way I just displayed the numbers, I did not find the index of each number.
Something like this?
A = [2, 2, 4, 1, 3; ...
3, 1, 10, 100, 200];
index = [];
for i1 = 1:size(A, 1)
for i2 = 1:size(A, 2)
index = [index; [i1 i2]];
end
end
Result:
index =
1 1
1 2
1 3
1 4
1 5
2 1
2 2
2 3
2 4
2 5
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

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2021a

Asked:

on 20 Jul 2021

Commented:

Jan
on 21 Jul 2021

Community Treasure Hunt

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

Start Hunting!