Atlab I am trying to write a script and currently I save a matrix

  • Thread starter Thread starter peterjaybee
  • Start date Start date
  • Tags Tags
    Matrix
AI Thread Summary
In MATLAB, to save a matrix to a file with a dynamic name based on a variable, you can use the syntax `save(['expt', int2str(exptnum), '.txt'], 'table', '-ascii' )`, where `exptnum` is the variable representing the experiment number. This method allows for automatic file naming without manual changes. For cases requiring leading zeros in the file names (like expt001), using `fprintf` or `num2str` is recommended for better formatting. The discussion also mentions the use of the `eval` command, although it is considered less elegant for this purpose. Additionally, there is a suggestion to move the topic to a more appropriate sub-forum for related inquiries.
peterjaybee
Messages
62
Reaction score
0
Hi, in MATLAB I am trying to write a script and currently I save a matrix to a .txt file using save('expt1.txt', 'table', '-ascii'). 'table' is the matrix I want to write to file.

This works fine, but I would like to make the file name to be 'exptn.txt', where n is a variable specified earlier in the script expt_no = n

In mathematica i could imput code in the following way.

"expt"<>expt_no<>".txt"

Can something similar be done in MATLAB or do I just have to change it manually each time?
 
Physics news on Phys.org


If you've got a script that runs through multiple experiments that you'd like saved, you could concatenate your textfile name along with the experiment numbering using int2str or num2str, for instance:

>>save(['expt', int2str(exptnum),'.txt'], 'table', '-ascii')

http://www.mathworks.com/help/techdoc/ref/int2str.html

There's also a nifty command (eval) that allows you to execute a string, but that's a rather inelegant way of doing what you seek to do:
http://www.mathworks.com/help/techdoc/ref/eval.html

EDIT: I've also asked a mod if they'd move this to the Math and Science Software sub-forum, where you might be able to find similar-type questions (for future reference)

Additionally, if you need leading zeros (e.g. expt001, expt010, expt100) you might be better off using fprintf or num2str, as mentioned in the documentation page linked above)
 
Last edited:

Similar threads

Replies
5
Views
3K
Replies
4
Views
2K
Replies
1
Views
2K
Replies
4
Views
14K
Replies
52
Views
12K
Replies
5
Views
9K
Back
Top