looping through sequential cell names

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|

looping through sequential cell names

djbrennan
Hello All,
I have a data file that produces many cell arrays with sequential names:
Y, Y1, Y2, Y3, ....... Y100.... etc.

I need to execute a series of calculations on each if these cell arrays. I would loke to write some type of loop that will operate on each cell array in succession, but don't know how.

I envision something along the lines of:
for i=1:100
    execute calculations on Yi
endfor

I know this is completely incorrect, though I hope it explains what I wish to accomplish.

Any help is greatly appreciated.
Reply | Threaded
Open this post in threaded view
|

Re: looping through sequential cell names

siko1056
Hi,

maybe you can try the "eval" command:

y1 = 1;
y2 = 2;
y3 = 3;
for i = 1:3
  eval (['y', num2str(i)])
end

HTH,
Kai
Reply | Threaded
Open this post in threaded view
|

Re: looping through sequential cell names

djbrennan
Thanks for your reply. I have had some success using eval to build variable name strings as you suggest. But I have seen many posts recommending against the use of eval. Do you have any thoughts on alternative solutions?

Thanks
Reply | Threaded
Open this post in threaded view
|

Re: looping through sequential cell names

Nir Krakauer-3
In reply to this post by djbrennan
Kai's solution should work, for example:

for i=1:100
    eval (['x = Y', num2str(i) ';'])

   ##do calculations on x, end up with z

   eval (['Z' num2str(i) ' = z;']) #copy result to Zi
endfor

_______________________________________________
Help-octave mailing list
[hidden email]
https://lists.gnu.org/mailman/listinfo/help-octave
Reply | Threaded
Open this post in threaded view
|

Re: looping through sequential cell names

Sebastian Schöps
In reply to this post by djbrennan
djbrennan wrote
But I have seen many posts recommending against the use of eval. Do you have any thoughts on alternative solutions?
Indeed, the usage of eval is not recommended due to many reasons.
However, once you have a setting as you described above there is no alternative. To avoid the setting you should not store  data in different variables in the first place. Alternatives are for example (cell) arrays or structs.

This is not Octave specific, you might want to have a look to classical programming literature or e.g. https://en.m.wikipedia.org/wiki/Eval