Combining two different size variables into one matrix
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Daria Ivanchenko
le 8 Oct 2020
Commenté : 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!
0 commentaires
Réponse acceptée
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
Plus de réponses (1)
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
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
Voir également
Catégories
En savoir plus sur Logical 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!