# Combining two different size variables into one matrix

8 views (last 30 days)
Daria Ivanchenko on 8 Oct 2020
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 on 8 Oct 2020
and then all you need is this:
>> 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
Daria Ivanchenko on 8 Oct 2020
Thank you very much! This function is awesome!

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);
Daria Ivanchenko on 8 Oct 2020
Thank you very much!