Concatenate content of cells containing vectors

1 回表示 (過去 30 日間)
Matthieu
Matthieu 2023 年 3 月 17 日
コメント済み: Matthieu 2023 年 3 月 18 日
Hello, is there a simpler way to produce this result without 'for loop' ?
Thanks a lot.
A{1,1} = [0 1] ;
A{2,1} = 2 ;
A{3,1} = [3 4 5 ];
disp(A)
{[ 0 1]} {[ 2]} {[3 4 5]}
B{1,1} = 10 ;
B{2,1} = [ ];
B{3,1} = [ 10 11 12];
disp(B)
{[ 10]} {0×0 double} {[10 11 12]}
out = horzcatcellmat(A,B);
disp(out)
{[ 0 1 10]} {[ 2]} {[3 4 5 10 11 12]}
C = {[ 100 200 300]};
disp(C)
{[100 200 300]}
out = horzcatcellmat(A,C);
disp(out)
{[ 0 1 100 200 300]} {[ 2 100 200 300]} {[3 4 5 100 200 300]}
function A = horzcatcellmat(A,B)
if nargin == 0
A{1,1} = 1 ;
A{2,1} = 2 ;
A{3,1} = [3 4 5 ];
B{1,1} = 10 ;
B{2,1} = [ ];
B{3,1} = [ 10 11 12];
out = horzcatcellmat(A,B);
disp(out)
C = {[ 100 200 300]};
out = horzcatcellmat(A,C);
disp(out)
else
if size(A,1) == 1 && size(B,1) > 1
A = repmat(A,[size(B,1),1]);
end
if size(B,1) == 1 && size(A,1) > 1
B = repmat(B,[size(A,1),1]);
end
assert(size(A,1), size(B,1),'Size of both arguments are not compatible')
sizY= size(A,1);
% --------- ORIGINAL QUESTION
for ind = 1 : sizY
A(ind) = {horzcat(A{ind},B{ind})};
end
% ---------
% EDIT WITH PROPOSED ANSWERS :
A = cellfun(@(a,b)[a,b], A,B,'UniformOutput',false); % Thx to Matt J
A = cellfun( @horzcat , A,B,'UniformOutput',false); % Thx to Stephen23
%
end
if nargout == 0
A=[];
end
end
  2 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 3 月 17 日
編集済み: Dyuman Joshi 2023 年 3 月 17 日
You might want to address cases when the number of inputs are not equal to 2 (Unless you are sure they won't occur) and the case where A has more rows than B.
Matthieu
Matthieu 2023 年 3 月 17 日
the 'assert' catches the case if A has not the same number of rows than B.
Indeed, the case if nargin == 1 is not handled...
However, the core question was: How to remove the for loop

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

採用された回答

Matt J
Matt J 2023 年 3 月 17 日
Simpler, yes. Faster, no.
A{1,1} = 1 ;
A{2,1} = 2 ;
A{3,1} = [3 4 5 ];
B{1,1} = 10 ;
B{2,1} = [ ];
B{3,1} = [ 10 11 12];
C=cellfun(@(a,b)[a,b], A,B,'uni',0)
C = 3×1 cell array
{[ 1 10]} {[ 2]} {[3 4 5 10 11 12]}
  3 件のコメント
Stephen23
Stephen23 2023 年 3 月 18 日
cellfun(@horzcat, A,B,'uni',0)
% ^^^^^^^^ simpler
Matthieu
Matthieu 2023 年 3 月 18 日
Thx Stephen23, simpler to read indeed (to my point of view)

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by