views:

56

answers:

3

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 so forth.

How do you set up declaring "newfilename" to have the variable "n" variable inside its name?

Thanks

+4  A: 
for n=1:100
    newfilename = ['NEW_FILE_' num2str(n) '.txt'];
end
zellus
+4  A: 

Or use SPRINTF in the for loop:

for n=1:100
    newfilename = sprintf('NEW_FILE_%d.txt',n);
end
yuk
+1  A: 

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.

Kena
You don't have to use cell array if newFilename supposed to be used only once inside the for-loop. The OP didn't say that he wanted to create newFilename1, newFilename2, etc. Good point anyway.
yuk
The question explicitly says "how to declare a variable name consisting of other variables"... I agree that the rest of the question is fuzzy, but that's what I was trying to address.
Kena
You are right, the title is very confusing.
yuk