dynamic name variable as the output of a function

9 Ansichten (letzte 30 Tage)
Clara
Clara am 9 Jan. 2013
Bearbeitet: Stephen23 am 19 Jun. 2019
Hello,
I have a function that I call several times, in a loop and I change the parameter, and I would like to change the output name.
For example, what I am doing is
for i=1:N
ipath=eval(sprintf('Pathname%d',i))
output_i=call_function(ipath)
end
where I have previously defined ipath as some string, for example Pathname1='\home\dir1\'; Pathname2='\home\dir2\'; Pathname3='\home\dir3\'; ... and so on.
And this works, but I want to also change the name of the output_i. That is, I would like to have output_1, output_2, etc., but I have failed until now.
I have tried several things using eval(), but nothing seems to work. I have also tried things like sprintf('output%d',i)=call_function(ipath)
but that doesn't work either. Does anybody have any ideas?
Thank you very much

Antworten (3)

Walter Roberson
Walter Roberson am 9 Jan. 2013

Jason Ross
Jason Ross am 9 Jan. 2013
If you are trying to process a series of files in a directory, there are a few examples here:
  1 Kommentar
Clara
Clara am 10 Jan. 2013
Hello Jason, First of all, thanks for answering. I read the links you put. I don't fully comprehend the dangers of eval(). I don't see the problem with the example in the link. But, if I should avoid eval(), do you have any ideas on what could be an alternative solution to my original question?
Thanks,

Melden Sie sich an, um zu kommentieren.


Thorsten
Thorsten am 9 Jan. 2013
This should do the job:
eval(['output' int2str(i) ' = call_function(ipath);'])
or
eval(['output' int2str(i) ' = call_function(Pathname' int2str(i) ');'])
A better alternative, because faster and more readable, would be to get rid of the eval by using something like
output(i) = call_function(pathname(i));
  1 Kommentar
Clara
Clara am 10 Jan. 2013
Bearbeitet: Clara am 10 Jan. 2013
This works perfectly! =) Thank you very much for your help.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by