Data splitting and saving to different variables
Show older comments
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 Comments
dpb
on 4 Jul 2022
Do NOT do this -- use the array indices instead...
Stephen23
on 4 Jul 2022
"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.
Answers (2)
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(1:8) = struct('data',[]);
for i_col = 1:size(M,2)
m(i_col).data = M(:,i_col);
end
m.data
% Note that splitting that little data in structured arrays is not very
% efficient
whos M
whos m
3 Comments
dpb
on 4 Jul 2022
"data in structured arrays is not very efficient"
In storage effeciency, no, but in coding efficiency and use as compared to the alternative posited, the savings are immense.
An even less efficient memory use but sitll more convenient programmatically, would be the table
>> array2table(M)
ans =
3×8 table
M1 M2 M3 M4 M5 M6 M7 M8
_______ _______ _______ ________ _______ _______ _______ ________
0.78085 0.4528 0.18342 0.10877 0.93074 0.16397 0.37596 0.012267
0.83353 0.1733 0.57372 0.81383 0.33064 0.54623 0.99263 0.46515
0.24278 0.31354 0.37909 0.061772 0.83759 0.19313 0.31973 0.1851
>> whos ans
Name Size Bytes Class Attributes
ans 3x8 2656 table
>>
But, the extra tools that come along with the table generally far outweigh the overhead cost.
Johan
on 4 Jul 2022
Ah yes I forgot to add the memory wise, thank you for the precision :)
dpb
on 4 Jul 2022
And, for good measure, with the table, OP gets the desired variable names coming along "for free"...
Steven Lord
on 4 Jul 2022
0 votes
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.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!