フィルターのクリア

Data splitting and saving to different variables

10 ビュー (過去 30 日間)
Adarsh
Adarsh 2022 年 7 月 4 日
コメント済み: Stephen23 2022 年 7 月 4 日
How to split a matrix data column wise and saving each column in different variable using loop. say M is a 3*8 matrix. I want to store these data of M columnwise into a 8 different column matrix, m1,m2,m3,m4,m5,m6,m7 and m8.
  2 件のコメント
dpb
dpb 2022 年 7 月 4 日
Do NOT do this -- use the array indices instead...
Stephen23
Stephen23 2022 年 7 月 4 日
"I want to store these data of M columnwise into a 8 different column matrix, m1,m2,m3,m4,m5,m6,m7 and m8."
You can certainly do that, if you want to force yourself into writing slow, complex, inefficient, obfuscated, insecure, buggy code that is hard to debug:
In contrast, indexing is simple and very efficient. So far you have not given any reason why you cannot use indexing.

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

回答 (2 件)

Johan
Johan 2022 年 7 月 4 日
You can use structure to do that, you can read more about it in the matlab help https://fr.mathworks.com/help/matlab/ref/struct.html
here is an example for your specific question:
M = rand(3,8)
M = 3×8
0.9703 0.0578 0.7766 0.9685 0.2685 0.3171 0.4461 0.7332 0.5987 0.5110 0.3488 0.3910 0.5700 0.3421 0.7714 0.2140 0.0907 0.6547 0.8126 0.9746 0.1461 0.2658 0.0747 0.8221
m(1:8) = struct('data',[]);
m = 1×8 struct array with fields:
data
for i_col = 1:size(M,2)
m(i_col).data = M(:,i_col);
end
m.data
ans = 3×1
0.9703 0.5987 0.0907
ans = 3×1
0.0578 0.5110 0.6547
ans = 3×1
0.7766 0.3488 0.8126
ans = 3×1
0.9685 0.3910 0.9746
ans = 3×1
0.2685 0.5700 0.1461
ans = 3×1
0.3171 0.3421 0.2658
ans = 3×1
0.4461 0.7714 0.0747
ans = 3×1
0.7332 0.2140 0.8221
% Note that splitting that little data in structured arrays is not very
% efficient
whos M
Name Size Bytes Class Attributes M 3x8 192 double
whos m
Name Size Bytes Class Attributes m 1x8 1088 struct
  3 件のコメント
Johan
Johan 2022 年 7 月 4 日
Ah yes I forgot to add the memory wise, thank you for the precision :)
dpb
dpb 2022 年 7 月 4 日
And, for good measure, with the table, OP gets the desired variable names coming along "for free"...

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


Steven Lord
Steven Lord 2022 年 7 月 4 日
Can you dynamically create variables with numbered names like x1, x2, x3, etc.? Yes.
Should you do this? The general consensus is no. That Answers post explains why this is generally discouraged and offers several alternative approaches.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by