How to save the elements of an array one at a time in a .mat file?
5 次查看(过去 30 天)
显示 更早的评论
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?
回答(1 个)
Abhishek GS
2015-4-17
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Workspace Variables and MAT-Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!