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!