Saving multiple variables in a mat file from loop

4 views (last 30 days)
I am trying to save multiple variables in a mat file from a loop. My loops has 10 iterations and every time I calculate 4 different variables. In every step all variables has the same size, ex. SE = [1,100], DE = [1,100], KE = [1,100] and CE = [1,100]. How can I save them all in every iteration?
  1 Comment
Stephen23
Stephen23 on 1 May 2017
Edited: Stephen23 on 1 May 2017
"How can I save them all in every iteration?"
Do you have a good reason for wanting to do that? It would be much more efficient to put all of those values into arrays, and then save the arrays after the loop. Simply use indexing to put the values into some preallocated arrays (indexing is very efficient) and then after the loop save the arrays using one save call (faster and more efficient than multiple calls).
Also read this:

Sign in to comment.

Answers (1)

KSSV
KSSV on 2 May 2017
n = 10 ; % loop count
filename='test.mat';
File = matfile(filename, 'Writable', true);
for i = 1:n
SE = rand(1,2) ;
DE = rand(1,3) ;
% save variables to file
File.SE(i,1:2) = SE ;
File.DE(i,1:3) = DE ;
end
clear File;
  1 Comment
Mario Santana
Mario Santana on 24 Jan 2019
Edited: Mario Santana on 25 Jan 2019
Good example, but what about SE = rand(2,2)?, I mean for matrix 2 dimensions plus loop dimension. Thanks.
-----------------------------------------------------------------------------------------------------------------------
Ok solved, using cells you can fit it into the requirements of matfiles.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!