How to save the elements of an array one at a time in a .mat file?

6 views (last 30 days)
Consider the following loop:
for i=1:100
X(i) = 2*i;
end
I would like to save the values of X, one iteration at a time, as and when it is generated, in a .mat file. This is the code I tried:
fopen('test.mat','a+');
for i=1:100
X(i) = 2*i;
save('test.mat','X(i)','-append')
end
This is the output I got 'X(i) is not a valid variable name'. When I try
save('test.mat','X','-append')
instead, I get the error 'Unable to write to MAT-file. File may be corrupted'. Is there a solution?

Answers (1)

Abhishek GS
Abhishek GS on 17 Apr 2015
Hi Sundar,
Assuming you need a representation of the variable and the iteration number in the .MAT file, you could try something like this.
for i=1:100
X(i) = 2*i;
varname=sprintf('X_%d',i);
assignin('caller',varname,2*i);
if (exist('test.mat'))
save('test.mat',varname,'-append')
else
save('test.mat',varname)
end
end
Hope this helps,
Abhishek

Community Treasure Hunt

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

Start Hunting!