How to save inner loop data with outer loop data in one matfile
1 view (last 30 days)
Show older comments
Hello Matlabers!
So basically i have this code
for i=1:5
r=5;
W = rand(m,r);
H = rand(r,n);
for rank=2:2:20 % Now for every value of rank I want to compute W0 and H0
W0 = rand(m,rank);
H0 = rand(rank,n);
end
% finally in the end I want to save all values. For each iteration of the OUTER loop,
% I will have all values of the INNER loop as well.
save( ['DATA/data_',int2str(i),'.mat'],'W','H','W0','H0','-v7.3' )
end
So i wish to have my matfile contain files like
Data_1
W,H
W0_2,W0_4,W0_6,...,W0_20
Data_2
W,H
W0_2,W0_4,W0_6,...,W0_20
.
.
Data_5
W,H
W0_2,W0_4,W0_6,...,W0_20
1 Comment
Stephen23
on 10 Jan 2019
"W0_2,W0_4,W0_6,...,W0_20"
Avoid creating variables with dynamic variable names:
It is much simpler and much more efficient to use indexing.
Accepted Answer
Stephen23
on 10 Jan 2019
Edited: Stephen23
on 10 Jan 2019
Using a structure (or any other array) is better than using dynamically named variables:
m = 2;
n = 3;
r = 5;
V = 2:2:20;
for ii = 1:5
W = rand(m,r);
H = rand(r,n);
S = struct();
for jj = 1:numel(V)
S(jj).W0 = rand(m,V(jj));
S(jj).H0 = rand(V(jj),n);
end
F = fullfile('DATA',sprintf('data_%d.mat',ii));
save(F,'W','H','S','V')
end
7 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!