Creating and naming arrays on the fly

5 views (last 30 days)
I have a vector composed of names. For each one of these names I want to create a separate array. Each name is to be called up from within a For loop and at that time populated with data from an external source using the "fetch" command, saved and then repeated for the name in the next row....etc.
Any idea how this can I can do this? Any help is more than appreciated.
Thanks.

Accepted Answer

TAB
TAB on 25 Jan 2012
If you have array names as string and want to create variables with the same name try eval() function.
See
>> doc eval
But eval is not recommended and should be avoided. See here why it is not recommented.

More Answers (1)

Oleg Komarov
Oleg Komarov on 24 Jan 2012
Use structures:
c = {'name1','name2','name3'};
for n = 1:numel(c)
s.(c{n}) = fetch...
end
Or read faq 4.6 to get a wider understanding what you might be tempted to do and how to avoid it (I showed you one way).
EDIT
for n = 1:numel(c)
s.(T(n,:)) = fetch(Connect,T(n,:),...
end
Be aware however that names for structure fields cannot start from a number.
  2 Comments
Carlos Freyre
Carlos Freyre on 25 Jan 2012
Oleg,
I tried your suggestion but it did not work. Not sure structure works in this case.
The vector of names is itself the result of filtering process that takes place earlier in the code and is stored as char in a dataset array T. Therefore, I do not name the array "c". My coding is:
for i=i:TickLength
T(i,:)= fetch(Connect,T(i,:),{'Close', 'Volume'},'DateFrom', 'DateTo');
i=i=1;
end
The error I get is:
Warning: Out of range or non-integer values truncated during conversion to character.
??? Subscripted assignment dimension mismatch.
what do you think?
Oleg Komarov
Oleg Komarov on 25 Jan 2012
You cannot assign results from fetch back to T(i,:) since they will most likely be cell arrays.
See my edit.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!