Saving Matrices Generated by Matlab Algorithm

Click For Summary
SUMMARY

This discussion focuses on saving matrices generated by a Matlab algorithm to files with dynamic names based on a loop counter. The user seeks to name files in the format "NAMEFILE-i" where "i" is the loop index. Key solutions include using the int2str function to convert the integer to a string and the sprintf function for formatted strings. Additionally, the fopen, fwrite, and fclose functions are essential for writing the matrix data to a binary file.

PREREQUISITES
  • Understanding of Matlab programming syntax
  • Familiarity with file I/O operations in Matlab
  • Knowledge of matrix data structures in Matlab
  • Experience with string manipulation functions in Matlab
NEXT STEPS
  • Learn how to use fopen and fwrite for different file formats in Matlab
  • Explore advanced string formatting techniques using sprintf in Matlab
  • Investigate how to save matrices in various formats, such as .mat and .csv
  • Study error handling in file operations to ensure robust Matlab scripts
USEFUL FOR

Matlab users, data scientists, and engineers who need to save algorithmically generated matrices to files with dynamic naming conventions.

PhilippH
Messages
12
Reaction score
0
Hi I have a question, I have to save to file the matrixs generated by an algorithm in Matlab. So i was wondering if is it possibile and how, to use in the filename a variable of the algorithm.

Let's say "i" is the counter of my cicle and i would like to save the matrix generated at every cicle to a file with the name NAMEFILE-i.

i.e.
for i=1:4
a=i;
save file-i a
end

Of course this is not working :-)

Do i need to use a string?
 
Physics news on Phys.org
you need to use the function int2str

mystr = int2str(i);

alternatively if you want to make the file name "NAMEFILE-i" then you can use

sprintf(mystr,'NAMEFILE-%i',i);

you'll have to check the syntax of this though, i can't remember it exactly off-hand. note that %i in the second argument refers to an integer type, not the variable i, whereas i in the last argument is the variable i.
 
By the way to output matrices to file...

outfile = fopen(int2str(i),'w');
dummy = fwrite(outfile,M,'float64');
fclose(outfile);

This saves the matrix M as binary data to the file 'i'
 
Ah thanks that was what I was looking for. Now I just need to fix how to save in the right format.
 

Similar threads

  • · Replies 18 ·
Replies
18
Views
6K
Replies
3
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 13 ·
Replies
13
Views
2K
  • · Replies 7 ·
Replies
7
Views
8K
  • · Replies 2 ·
Replies
2
Views
5K