How to concatenate matrices when some of them can be empty?

15 ビュー (過去 30 日間)
Leon
Leon 2021 年 12 月 15 日
コメント済み: Leon 2021 年 12 月 15 日
I have 10 matrices, each of them would either have a size of n by 12, or is empty. For example: T1 can be a matrix with a size of 100 x 12, but it can also be []. The same thing goes true for T2, ... T10.
What is the best way to put them together like the below?
vertcat(T1, T2, T3, ... T10)
Many thanks!

採用された回答

Image Analyst
Image Analyst 2021 年 12 月 15 日
I'd do it almost like you. This works fine and has 9 rows because T7 is empty.
T1 = rand(1, 12);
T2 = rand(1, 12);
T3 = rand(1, 12);
T4 = rand(1, 12);
T5 = rand(1, 12);
T6 = rand(1, 12);
T7 = [];
T8 = rand(1, 12);
T9 = rand(1, 12);
T10 = rand(1, 12);
tallerMatrix = vertcat(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)

その他の回答 (1 件)

Voss
Voss 2021 年 12 月 15 日
make the empty matrices 0-by-12, then you can vertcat them like normal.
if isempty(T2)
T2 = zeros(0,12);
end
% and so on
  3 件のコメント
Edric Ellis
Edric Ellis 2021 年 12 月 15 日
zeros(0,12) generates an empty matrix with the right number of columns. When you vertcat this, it disappears. Like this:
T1 = rand(1, 4);
T2 = zeros(0, 4);
T3 = 10 + rand(1, 4);
vertcat(T1, T2, T3)
ans = 2×4
0.0375 0.3622 0.0174 0.9187 10.5569 10.8928 10.4045 10.8303
Making the right number of columns is not strictly necessary in this case, since vertcat knows how to ignore [] which is of size [0 0].
Leon
Leon 2021 年 12 月 15 日
Many thanks!
Interesting to hear the behavior of zeros when vertcating.

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

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by