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

조회 수: 9 (최근 30일)
Sundar Aditya
Sundar Aditya 2015년 4월 16일
답변: Abhishek GS 2015년 4월 17일
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
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

카테고리

Help CenterFile 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!

Translated by