Concatenating cells according an external vector

I am trying to do some work on simulating particles. We label the particles say 1 to n. In each time frame there is a chance that particle i undergoes more than one collision and I'd like to capture this data in an easy way. I have two vectors A and B, where B is in ascending order. The rule is that the particle whose number is given by B(i) collides with particle A(i).
Typicall example might be
A = [7;3;4;13;20;3;1]
B = [11;11;11;15;15;24;24]
I'd like to find an easy way of being able to draw in the data that tells me which particle hit particle B(i) for each unque B(i). My idea is to creat a cell that concactenates entries of A accoriding to the corrresponding entry of B. But I can't seem to do this.
What I hope to get would be a cell
E = {[7,3,4];[13,20];[3,1]}.
I tried the follwing code but I keep getting that "Index exceeds the number of array elements." error.
m = length(unique(B))
E = cell(1,m)
C = unique(B)
for i=1:m %C(i) is the ith unique entry of B
while B(j) == C(i)
E{i} = cat(2,E{i},A(j));
end
end

 採用された回答

Matt J
Matt J 2023 年 3 月 4 日
編集済み: Matt J 2023 年 3 月 4 日

1 投票

A = [7;3;4;13;20;3;1];
B = [11;11;11;15;15;24;24];
E=splitapply(@(x) {x}, A, findgroups(B));
E{:}
ans = 3×1
7 3 4
ans = 2×1
13 20
ans = 2×1
3 1

6 件のコメント

Milos
Milos 2023 年 3 月 4 日
Ahh thanks for this and teaching me about two new functions.
Dyuman Joshi
Dyuman Joshi 2023 年 3 月 4 日
A = [7;3;4;13;20;3;1];
B = [11;11;11;15;15;24;24];
%I'm not sure if what OP mentioned is a typo or not
E=splitapply(@(x) {x'}, A, findgroups(B))
E = 3×1 cell array
{[7 3 4]} {[13 20]} {[ 3 1]}
Milos
Milos 2023 年 3 月 4 日
Whatdo you mean sorry. Have I missed something here. Many Thanks.
Matt J
Matt J 2023 年 3 月 4 日
If you want the subsets of A to be row vectors instead of column vectors, use @(x) {x'} or @(x) {x(:).'}.
Dyuman Joshi
Dyuman Joshi 2023 年 3 月 4 日
編集済み: Dyuman Joshi 2023 年 3 月 4 日
You mentioned in your question -
"What I hope to get would be a cell"
E = {[7,3,4];[13,20];[3,1]}
E = 3×1 cell array
{[7 3 4]} {[13 20]} {[ 3 1]}
Here each cell elements are row vectors not column vectors as they should be as A is a column vector. (which could have been a typo)
Milos
Milos 2023 年 3 月 4 日
Ahh yes I see now. I am quite new to coding and didn't notice this subtlety. I happens that it didn't make a difference to my proceeding code. Thank you for your help!

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

その他の回答 (0 件)

カテゴリ

タグ

質問済み:

2023 年 3 月 4 日

コメント済み:

2023 年 3 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by