-2

I have a bunch of variables called length_act_i where

i=1:6

I'd like to call each one sequentially as part of a for loop, but this doesn't work:

for i=1:6
    I={['length_act_',num2str(i)]};
    subplot(3,2,i)
    [f x]=hist(I,1:2:5);
    bar(x,f./trapz(x,f),'barwidth',0.5,'r');
end

What's the most efficient way to do this?

Regards,

HCAI
  • 2,213
  • 8
  • 33
  • 65

1 Answers1

5

Use eval inside your loop:

eval(['I = length_act_', num2str(i)]);

Pro tip:
The eval command is usually slow and inefficient, use arrays instead. In your case, it seems that each of your "length_act_i" variables is a vector on its own, so you should be employing a cell array. For instance, call it length_act and set it like so:

length_act = {length_act_1, length_act_2, length_act_3, ...};

and then access each cell in the array using:

for i = 1:length(length_act)
    I = length_act{i};

    ...
end

Also, it is recommended not to use "i" and "j" as names for variables.

Community
  • 1
  • 1
Eitan T
  • 32,660
  • 14
  • 72
  • 109
  • 1
    +1 for decrypting this question. – Shai Mar 17 '13 at 16:58
  • 1
    +1 for being faster... – H.Muster Mar 17 '13 at 17:01
  • 1
    This is extremely helpful, thank you. I've been using all sorts of makeshift methods of accessing and storing data but never properly understood one method over another. It also solved another question of how to add different length vectors to a single array. Amazingly quick too! :) – HCAI Mar 17 '13 at 17:08
  • Actually, a quick question. If I had 1000 vectors length_act_1...1000 how would you efficiently pop them into length_act? – HCAI Mar 17 '13 at 17:09
  • 1
    @user1134241 You should be generating `length_act` _instead_ of creating 1000 variables. If you cannot modify your code accordingly, resort to `eval`. – Eitan T Mar 17 '13 at 17:26