How to create a string using a loop variable in MATLAB?

I have a loop like this:

for i=1:no %some calculations fid = fopen('c:\\out.txt','wt'); %write something to the file fclose(fid); end 

I want the data to be written to different files:

  • for i=1 , data is written to out1.txt
  • for i=2 , data is written to out2.txt
  • for i=3 , the data is written to out3.txt
  • and etc.

Doing 'out'+ i does not work. How can I do that?

+4
source share
4 answers

Another option would be the SPRINTF function:

 fid = fopen(sprintf('c:\\out%d.txt',i),'wt'); 
+5
source

filename = strcat('out', int2str(i), '.txt');

+3
source

Have you tried:

 int2str(i) 
+1
source

Simply put:

 for i=1:no %some calculations fid = fopen(['c:\out' int2str(i) '.txt'],'wt'); %write something to the file fclose(fid); end 

PS. I do not believe that Matlab strings require escaping, except for '' (unless it is a format string for * printf style functions)

EDIT: see comment by @MatlabDoug

0
source

All Articles