Combining multiple matrices into a single vector

8 ビュー (過去 30 日間)
Scott Banks
Scott Banks 2023 年 9 月 29 日
編集済み: Voss 2023 年 9 月 29 日
Hi there,
have some matrices that I would like to combine into a single vector. For example:
T1 = [2 3;
4 2]
T2 = [1 7;
9 4]
T3 = [5 5;
1 4]
I do not want to add them together like it does here:
T = [T1 T2 T3]
Rather I want to store them is such a way that I can index them in a loop
How can I accomplish this?
Many thanks
  2 件のコメント
Katy
Katy 2023 年 9 月 29 日
Hi Scott-
How do you want the final matrix to look? Can you provide an example of the desired final matrix?
Is it a single row? Or a combined matrix?
Thanks,
Katy
Stephen23
Stephen23 2023 年 9 月 29 日

“How can I accomplish this?“

Either use a cell array or a 3D array.

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

採用された回答

Star Strider
Star Strider 2023 年 9 月 29 日
編集済み: Star Strider 2023 年 9 月 29 日
A single vector is not possible, however a 3D array is with the cat function —
T1 = [2 3;
4 2];
T2 = [1 7;
9 4];
T3 = [5 5;
1 4];
T = cat(3, T1, T2, T3)
T =
T(:,:,1) = 2 3 4 2 T(:,:,2) = 1 7 9 4 T(:,:,3) = 5 5 1 4
T = reshape(T, 2, []) % Another Option
T = 2×6
2 3 1 7 5 5 4 2 9 4 1 4
EDIT — (29 Sep 2023 at 11:56)
Added the reshape option.
.

その他の回答 (1 件)

Katy
Katy 2023 年 9 月 29 日
編集済み: Katy 2023 年 9 月 29 日
If I am understanding the question correctly, here's one way to store them as a single vector (T_vec).
It requires storing the inputs in a cell array rather than separate matrices.
Let me know if this solves your question!
T{1,1} = T1;
T{2,1} = T2;
T{3,1} = T3;
T_vec = [];
for i = 1:length(T)
temp = T{i,1};
sz_temp = size(temp);
rows = sz_temp(1,1);
col = sz_temp(1,2);
for j = 1:rows
for p = 1:col
T_vec = [T_vec temp(j, p)];
end
end
end
  1 件のコメント
Voss
Voss 2023 年 9 月 29 日
編集済み: Voss 2023 年 9 月 29 日
@Katy: That can be simplified a bit:
T1 = [2 3;
4 2];
T2 = [1 7;
9 4];
T3 = [5 5;
1 4];
T = {T1;T2;T3};
for ii = 1:numel(T)
T{ii} = reshape(T{ii}.',1,[]);
end
T_vec = [T{:}]
T_vec = 1×12
2 3 4 2 1 7 9 4 5 5 1 4
Or, to simplify even further:
T = {T1;T2;T3};
T_vec = reshape(vertcat(T{:}).',1,[])
T_vec = 1×12
2 3 4 2 1 7 9 4 5 5 1 4

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by