Reputation: 83
consider a matrix:
a = [1 2
1 3
2 3
4 5
6 1]
I want to find duplicates for every unique element of a
and take the rows of them to different matrices. For example here lets say that the answer for number 1 is:
a1 = [1 2
1 3
6 1]
The answer for number 2 is:
a2 = [1 2
2 3]
The answer for number 3 is:
a3 = [1 3
2 3]
and so on for every unique elements of matrix a
. Any suggestions?
Upvotes: 0
Views: 325
Reputation: 19689
This will do it:
temp=unique(a);
for k=1:numel(temp)
[r,~]=find(a==temp(k));
assignin('base', ['a' num2str(k)], a(sort(r),:))
end
Results:-
>> a1
a1 =
1 2
1 3
6 1
>> a2
a2 =
1 2
2 3
>> a3
a3 =
1 3
2 3
>> a4
a4 =
4 5
>> a5
a5 =
4 5
>> a6
a6 =
6 1
Upvotes: 1
Reputation: 65470
You can use any
to check if any element of a row contains the value you want. This will return a logical array that is true
where the row contained the value. You can then use this to grab the relevant rows of a
.
result = a(any(a == value, 2), :);
We could create an anonymous function that does this for you.
rows_that_contain_value = @(A, value)A(any(A == value, 2), :);
Then we can use this like this
a = [1 2
1 3
2 3
4 5
6 1]
a1 = rows_that_contain_value(a, 1);
a2 = rows_that_contain_value(a, 2);
a3 = rows_that_contain_value(a, 3);
If we want to do this for all unique values in a
, we can do something like the following.
groups = arrayfun(@(x)rows_that_contain_value(a, x), unique(a), 'uniformoutput', 0);
Upvotes: 0