Lazer
Lazer

Reputation: 94830

How do I 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 data to be written to different files like this:

Doing 'out'+ i does not work. How can this be done?

Upvotes: 4

Views: 4341

Answers (4)

KitsuneYMG
KitsuneYMG

Reputation: 12901

More simply:

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

end

PS. I don't believe Matlab strings need escaping except for '' (unless it's a format string for *printf style functions)

EDIT: See comment @MatlabDoug

Upvotes: 0

gnovice
gnovice

Reputation: 125854

Yet another option would be the function SPRINTF:

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

Upvotes: 5

Dan Vinton
Dan Vinton

Reputation: 26769

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

Upvotes: 3

Richard Morgan
Richard Morgan

Reputation: 7681

Did you try:

int2str(i)

Upvotes: 1

Related Questions