フィルターのクリア

adding counts of ordered pairs

1 回表示 (過去 30 日間)
Barbara Margolius
Barbara Margolius 2022 年 9 月 6 日
コメント済み: Bruno Luong 2022 年 9 月 6 日
I have a sequence of by 3 arrays, say , , , that are generated within a loop. That is, the number of rows of each array varies, but each array has three columns. The first two columns represent ordered pairs. The third column is the count of those ordered pairs. I want to "add" these together so that I get an array that accumulates the counts of these ordered pairs into a new array that is with the same structure. For example, if is
A1=[1 4 3;
3 5 1;
12 4 7;
13 5 2;
14 1 1];
and is
A1=[1 5 1;
13 5 1;
13 7 3;
14 1 5];
then the cumulative matrix should be
A=[1 4 3;
1 5 1;
3 5 1;
12 4 7;
13 5 3;
13 7 3;
14 1 6];
The arrays being "summed" in this way have hundreds of entries and are themselves summaries of arrays with thousands of entries, so efficiency matters.

採用された回答

Bjorn Gustavsson
Bjorn Gustavsson 2022 年 9 月 6 日
One way to go about this is to use sparse:
A1 = [1 4 3;
3 5 1;
12 4 7;
13 5 2;
14 1 1];
A2 = [1 5 1;
13 5 1;
13 7 3;
14 1 5];
A_all = sparse([A1(:,1);A2(:,1)],[A1(:,2);A2(:,2)],[A1(:,3);A2(:,3)]);
[I1,I2,Val] = find(A_all);
[~,idx1] = sort(I1);
disp([I1(idx1),I2(idx1),Val(idx1)])
HTH
  2 件のコメント
Barbara Margolius
Barbara Margolius 2022 年 9 月 6 日
編集済み: Barbara Margolius 2022 年 9 月 6 日
I am going to time both your answer and Bruno's to see which works best. I accepted yours because I suspect with my data it will be faster.
Bruno Luong
Bruno Luong 2022 年 9 月 6 日
This will save you a sort
A1 = [1 4 3;
3 5 1;
12 4 7;
13 5 2;
14 1 1];
A2 = [1 5 1;
13 5 1;
13 7 3;
14 1 5];
A_all = sparse([A1(:,2);A2(:,2)],[A1(:,1);A2(:,1)],[A1(:,3);A2(:,3)]);
[I2,I1,Val] = find(A_all);
A = [I1,I2,Val]
A = 7×3
1 4 3 1 5 1 3 5 1 12 4 7 13 5 3 13 7 3 14 1 6

サインインしてコメントする。

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2022 年 9 月 6 日
編集済み: Bruno Luong 2022 年 9 月 6 日
A1=[1 4 3;
3 5 1;
12 4 7;
13 5 2;
14 1 1];
A2=[1 5 1;
13 5 1;
13 7 3;
14 1 5];
A12=[A1; A2];
[A12u,~,J]=unique(A12(:,1:2),'rows','stable');
A=[A12u,accumarray(J,A12(:,3))]
A = 7×3
1 4 3 3 5 1 12 4 7 13 5 3 14 1 6 1 5 1 13 7 3
  7 件のコメント
Bjorn Gustavsson
Bjorn Gustavsson 2022 年 9 月 6 日
@Bruno Luong: The amount of subconsious/implicit assumptions I make when writing QD-solutions is a bit frightening.
Bruno Luong
Bruno Luong 2022 年 9 月 6 日
That's called "intuition".

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by