Combining two different size variables into one matrix

13 vues (au cours des 30 derniers jours)
Daria Ivanchenko
Daria Ivanchenko le 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!

Réponse acceptée

Stephen23
Stephen23 le 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
  1 commentaire
Daria Ivanchenko
Daria Ivanchenko le 8 Oct 2020
Thank you very much! This function is awesome!

Connectez-vous pour commenter.

Plus de réponses (1)

Ameer Hamza
Ameer Hamza le 8 Oct 2020
Modifié(e) : Ameer Hamza le 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 commentaires
Ameer Hamza
Ameer Hamza le 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
Daria Ivanchenko
Daria Ivanchenko le 8 Oct 2020
Thank you very much!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by