d4rty
d4rty

Reputation: 4178

MATLAB - how to take a string as an argument for a function

How can I include the string filename to the fopen function? See code and comments below.

for i=1:5
  filename = strcat('Cali',num2str(i)); 
  %first iteration: filename = Cali1          
  %instead of result.txt there should be Cali1.txt in the following statement, but i want to achieve this by using the string filename 

  fid = fopen( 'results.txt', 'wt' );
  fprintf( fid, 'write something');
  fclose(fid);
end

Upvotes: 0

Views: 67

Answers (1)

houtanb
houtanb

Reputation: 4100

This is basic Matlab functionality. You should read the manual a bit more closely. That said, here's the code you need:

for i=1:5
  fid = fopen(['Cali' num2str(i) '.txt'], 'wt');
  fprintf(fid, 'write something');
  fclose(fid);
end

If you want to use strcat, just add the line filename = strcat('Cali', num2str(i), '.txt'); in the code you had above.

Upvotes: 2

Related Questions