5

Create more than one text file using fopen Matab in a loop

 2 years ago
source link: https://www.codesd.com/item/create-more-than-one-text-file-using-fopen-matab-in-a-loop.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Create more than one text file using fopen Matab in a loop

advertisements

I'm quite new to Matlab and programming in general and would love to get some help with the following. I've look here on the website, but couldn't find an answer.

I am trying to use a for-loop and fprintf to give me a bunch of separate text files, whose file names contain the index I use for my for-loop. See for example this piece of code to get the idea of what I'd like to do:

for z=1:20
    for x=1:z;
        b=[x exp(x)];
        fid = fopen('table z.txt','a');
        fprintf(fid,'%6.2f, %6.2f\n',b);
        fclose(fid);
    end
end

What I'm looking for, is a script that (in this case) gives me 20 separate .txt files with names 'table i.txt' (i is 1 through 20) where table 1.txt only contains [1, exp(1)], table 2.txt contains [1, exp(1)] \newline [2, exp(2)] and so on.

If I run the script above, I get only one text file (named 'table z.txt' with all the data appended underneath. So the naming of fopen doesn't 'feel' the z values, but interprets z as a letter (which, seeing the quotation marks doesn't really surprise me)

I think there must be an elegant way of doing this, but I haven't been able to find it. I hope someone can help. Best, L


use num2str and string concatenation [ ... ].

fid = fopen( ['table ' num2str(z) '.txt'],'a');


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK