Create .mat file which appends a variable each time a function is executed
이전 댓글 표시
Hi
I have a matlab code which contains functions (function()) and it runs until stopped. The code watches for files to be added to a directory and then executes the functions that follows. One of the functions does calculations and then has an output of 4 different variables. I want to save these variables in a directory on my PC. So Basically I want to create an empty .mat file, and then as a new file gets added and the script runs, the new values for these 4 variable should be appended to the .mat file in matrix form if possible. I have tried but did not get it right. Can someone please help
Thank you
채택된 답변
추가 답변 (1개)
.mat files aren't sequential files; the "save -append" syntax doesn't add to an existing variable; it adds a new variable to the existing .mat file. If the same variable name is used, then it overwrites the variable of that name such that you'll end up only with the last iteration of your variables being saved. There's no way around this with a .mat file other than the very expensive alternative of reading the existing variables into memory, appending the new values to those and then rewriting.
You need another storage scheme; probably the better choice would be to simply open a file at the beginning of the script/function and then close it when done. It will be more efficient if the variables were collected as an array, but for only four it's not too terrible to code otherwise.
...
permiss=input('New File (N[ew])?','s') % user choice to overwrite/append
if startsWith(permiss,'N','ignorecase',1) % your choice how to decide which
p='w';
else
p='a';
end
fid=fopen(fullfile('foldername','filename.bin'),p); % open a file for output
while(continuesflag) % runs until...
...
[a,b,c,d]=yourfunction(inputs); % do computations
fwrite(fid,[a b c d]) % and output them
...
end
fid=fclose(fid); % close when done
댓글 수: 1
Stephen23
2023년 8월 15일
"There's no way around this with a .mat file other than the very expensive alternative of reading the existing variables into memory, appending the new values to those and then rewriting."
카테고리
도움말 센터 및 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!