extracting from a matrix

1 vue (au cours des 30 derniers jours)
giuseppe insignito
giuseppe insignito le 1 Déc 2020
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 commentaire
giuseppe insignito
giuseppe insignito le 1 Déc 2020
Modifié(e) : giuseppe insignito le 1 Déc 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
. .
. .
. .

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 1 Déc 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]

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by