How to save the elements of an array one at a time in a .mat file?
조회 수: 9 (최근 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!