I have a Variable that needs to be dependent on another variable inside a loop:
for n=1:100
newfilename="NEW_FILE_1.txt"
end
where the "1" needs to be what ever n is: So 1 for the first loop and 2 for the second loop and so on and开发者_JAVA百科 so forth.
How do you set up declaring "newfilename" to have the variable "n" variable inside its name?
Thanks
for n=1:100
newfilename = ['NEW_FILE_' num2str(n) '.txt'];
end
Or use SPRINTF in the for loop:
for n=1:100
newfilename = sprintf('NEW_FILE_%d.txt',n);
end
If I get your question correctly, you want, at the end of the loop, to have a series of variables called newfilename1, newfilename2... etc.
The short answer to this is: don't*. Instead, place your data in an cell array as follows
for n=1:100
newFilename{n} = sprintf('NEW_FILE_%i.txt', n)
end
You can then refer to your variables as newfilename{1}, newFilename{2}, etc...
* There is a way to do what you want using the function eval, and the method has been answered in other posts. But it's just bad practice.
精彩评论