extracting from a matrix

1 view (last 30 days)
I have a matrix:
XY_indx =
1 1 1
2 1 2
1 2 3
2 2 4
1 1 5
2 1 6
1 2 7
2 1 10
1 2 11
Let's say that first and second column of the previous matrix represent coordinates, while the third is the index. I need to collect, into extra arrays, all the indexes which have same coordinates. In this case v1 = [1 5] v2 = [2 6] v3 = [3 7] ...
If simpler you can also put the couples into a single matrix, like:
v =
1 5
2 6
3 7
. .
. .
. .
thanks!
  1 Comment
giuseppe insignito
giuseppe insignito on 1 Dec 2020
Edited: giuseppe insignito on 1 Dec 2020
what if I do not only need the index but also combos of each couple? According to the exaple I made:
v1 = [1 5]
v2 = [5 1]
v3 = [2 6]
v4 = [6 2]
v5 = ...
or
v =
1 5
5 1
. .
. .
. .

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 1 Dec 2020
XY_indx = [
1 1 1
2 1 2
1 2 3
2 2 4
1 1 5
2 1 6
1 2 7
2 1 10
1 2 11];
output = accumarray(XY_indx(:,1:2), XY_indx(:,3), [], @(V) {V})
output = 2x2 cell array
{2×1 double} {3×1 double} {3×1 double} {[ 4]}
output{2,1}
ans = 3×1
2 6 10
Notice that some of your groups have more than 2 entries.
This works only if the indices are positive integers, and it does not work well if the indices have large gaps (you get empty cells).
There are variations for the times those are problems:
[urow, ~, G] = unique(XY_indx(:,1:2), 'rows');
grouped = accumarray(G, XY_indx(:,3), [], @(V) {V.'});
output = [num2cell(urow,2), grouped]
output = 4x2 cell array
{1×2 double} {1×2 double} {1×2 double} {1×3 double} {1×2 double} {1×3 double} {1×2 double} {[ 4]}
Here, the first column of the cell gives the coordinates such as [2 1] that the second column of the cell refers to. The second column of the cell lists the entries such as [2, 6, 10]

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!