Combining two different size variables into one matrix

12 views (last 30 days)
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!

Accepted Answer

Stephen23
Stephen23 on 8 Oct 2020
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

More Answers (1)

Ameer Hamza
Ameer Hamza on 8 Oct 2020
Edited: Ameer Hamza on 8 Oct 2020
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 Comments
Ameer Hamza
Ameer Hamza on 8 Oct 2020
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

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!