Combining two different size variables into one matrix

13 ビュー (過去 30 日間)
Daria Ivanchenko
Daria Ivanchenko 2020 年 10 月 8 日
コメント済み: Daria Ivanchenko 2020 年 10 月 8 日
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 件のコメント
Daria Ivanchenko
Daria Ivanchenko 2020 年 10 月 8 日
Thank you very much! This function is awesome!

サインインしてコメントする。

その他の回答 (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
Daria Ivanchenko
Daria Ivanchenko 2020 年 10 月 8 日
Thank you very much!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by