Combining two different size variables into one matrix

6 次查看(过去 30 天)
Hi!
I have two variables of different size. Let's suppose A is the size of 1x5 and B is the size of 1x8. I want to make a matrix where the first row will be A, and the second raw will be B. The matrix should be the size of 2x8 where the last columns of the first row are replaced with NaNs. For example:
A = [1 2 3 4 5]
B = [1 2 3 4 5 6 7 8]
C = [1 2 3 4 5 NaN NaN NaN; 1 2 3 4 5 6 7 8]
How can I do this?
Thanks!

采纳的回答

Stephen23
Stephen23 2020-10-8
The simplest solution is to download this:
and then all you need is this:
>> A = [1,2,3,4,5];
>> B = [1,2,3,4,5,6,7,8];
>> C = padcat(A,B)
C =
1 2 3 4 5 NaN NaN NaN
1 2 3 4 5 6 7 8

更多回答(1 个)

Ameer Hamza
Ameer Hamza 2020-10-8
编辑:Ameer Hamza 2020-10-8
Try this
A = [1 2 3 4 5];
B = [1 2 3 4 5 6 7 8];
M = {A, B}; % combine all variables in a cell array
n = max(cellfun(@numel, M));
M = cellfun(@(x) {[x nan(1,n-numel(x))]}, M(:));
C = cell2mat(M);
  3 个评论
Ameer Hamza
Ameer Hamza 2020-10-8
My code works in this case too
A = [1 2 3 4 5 6 7 8; 1 2 3 4 5 NaN NaN NaN];
B = [1 2 3 4 5];
M = {A, B};
n = max(cellfun(@(x) size(x, 2), M));
M = cellfun(@(x) {[x nan(1,n-numel(x))]}, M(:));
C = cell2mat(M);
Result
>> C
C =
1 2 3 4 5 6 7 8
1 2 3 4 5 NaN NaN NaN
1 2 3 4 5 NaN NaN NaN

请先登录,再进行评论。

类别

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