Combining arrays of different row length

조회 수: 4 (최근 30일)
ScGold
ScGold 2019년 2월 13일
편집: Jan 2019년 2월 13일
I have 3 arrays:
A = [1;2;3]
B = [1;2;3;4]
C = [1;2]
I want to combine these to create a new array:
D =
1 1 1
2 2 2
3 3 NaN
NaN 4 NaN
Thank you!

답변 (2개)

madhan ravi
madhan ravi 2019년 2월 13일
ABC={A,B,C};
MAX=max(cellfun(@numel,ABC));
D=cell2mat(cellfun(@(x)[x;nan(MAX-numel(x),1)],ABC,'un',0))

Jan
Jan 2019년 2월 13일
편집: Jan 2019년 2월 13일
With a simple loop:
function A = CatWithPadding(varargin)
C = varargin;
nC = numel(C);
len = cellfun('prodofsize', C); % Faster than: @numel
A = nan(max(len), nC)
for k = 1:nC
A(1:len(k), k) = C{k}(:);
end
end
Now call this like:
M = CatWithPadding(A, B, C)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by