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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by