extracting from a matrix

조회 수: 1 (최근 30일)
giuseppe insignito
giuseppe insignito 2020년 12월 1일
답변: Walter Roberson 2020년 12월 1일
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
giuseppe insignito
giuseppe insignito 2020년 12월 1일
편집: giuseppe insignito 2020년 12월 1일
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
. .
. .
. .

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2020년 12월 1일
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]

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by