0

I have a list of files that have data ...

    foo1.txt
    foo2.txt
    ...
    fooN.txt

I extract the data in these files

    foo1
    foo2
    ...
    fooN

I now want to pass these variables to a function

   for i = 1:N
       % This is what I want: asdf = fooi
       function(asdf)
   end

I tried sprintf, and also

    asdf = ['foo' num2str(i)]

But these make the variable asdf a char, instead of a double like fooi.

Thanks in advance.

-gsandhu

gsandhu
  • 489
  • 5
  • 13

2 Answers2

2

Immidiate solution

asdf = eval( sprintf('foo%d',i) );

However this is not a good practice in general.
What you should do is read the files into cell-elements foo{1} will have the contents of foo1.txt, foo{2} will have the contents of foo2.txt and so on. This way you can simply access foo{i} and get the data you need.

PS,
It is best not to use i as a variable name in Matlab.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
  • 1
    2.) And more importantly, thank you for the cell array suggestion. – gsandhu Nov 19 '13 at 18:18
  • 1
    @gsandhu I'm happy I could assist. If this solution works for you, please consider "accepting" it be clicking the "V" icon beside it. – Shai Nov 19 '13 at 20:42
0

You can use eval function

eval(['foo' num2str(i)])

P0W
  • 46,614
  • 9
  • 72
  • 119