How to concatenate horizontally a cell into another cell based on a vector

3 views (last 30 days)
Hi,
I want to concatenate horizzontally with a criteria based on a vector this cell into another cell. All the double matrices inside the "wl_tmp" cell have the same number of rows, but not the same number of colums!
I have this vector and in my idea, the elements with the same value should be grouped together (concatenating them horizontally from left to right).
For example: the final cell is "wl_final":
wl_final{1} = [wl_tmp{1}, wl_tmp{2}, wl_tmp{3}, wl_tmp{4}, wl_tmp{5}, wl_tmp{6}, wl_tmp{7}, wl_tmp{8}, wl_tmp{9}, wl_tmp{10}, wl_tmp{11}];
wl_final{2} = [wl_tmp{12}, wl_tmp{13}];
%and so on...
I found a solution with a for loop but because of the high amount of data, it's terribly slow and I wanted to figure out how I could use "accumarray" instead, but I cannot understand how that function works exactly and how to use it for my purposes.
wl_tot = length(wl_idx);
wl_final = cell(1,length(pX_i_ref_wl)); %"pX_i_ref_wl" contains just the name of the groups: in this case is a 1x11 string
clear tmp;
for k=1:wl_tot
if wl_idx(k)~=wl_idx(max(k-1,1)) || k==1
tmp = wl_tmp{k};
else
tmp = [tmp, wl_tmp{k}]; %#ok<AGROW>
end
if k==wl_tot || wl_idx(k+1)~=wl_idx(k)
wl_final{wl_idx(k)} = tmp;
clear tmp;
end
end
P.S. I cannot group them before, because the "wl_tmp" comes from a parfor loop with sliced variables and I'd prefer to group them later!

Accepted Answer

Stephen23
Stephen23 on 13 Apr 2021
Edited: Stephen23 on 13 Apr 2021
X = [1,1,2,2];
C = {rand(3,2),rand(3,1),rand(3,2),rand(3,1)};
C{:}
ans = 3×2
0.3878 0.8399 0.9283 0.7467 0.7731 0.5606
ans = 3×1
0.5279 0.0653 0.8680
ans = 3×2
0.5664 0.3253 0.0695 0.4880 0.0237 0.4730
ans = 3×1
0.5007 0.0762 0.1294
Method one: arrayfun
F = @(x)[C{x==X}];
D = arrayfun(F,1:max(X),'uni',0);
D{:}
ans = 3×3
0.3878 0.8399 0.5279 0.9283 0.7467 0.0653 0.7731 0.5606 0.8680
ans = 3×3
0.5664 0.3253 0.5007 0.0695 0.4880 0.0762 0.0237 0.4730 0.1294
Method two: accumarray
Y = 1:numel(X);
F = @(y){[C{y}]};
D = accumarray(X(:),Y(:),[],F);
D{:}
ans = 3×3
0.3878 0.8399 0.5279 0.9283 0.7467 0.0653 0.7731 0.5606 0.8680
ans = 3×3
0.5664 0.3253 0.5007 0.0695 0.4880 0.0762 0.0237 0.4730 0.1294

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!