Adding arrays found using 'who' function

Hello,
I have used the 'who' function to obtain the required 2D numeric arrays from a list of variables, like this;
Find_Target_Vars = who ('Target_Str')
Find_Target_Vars =
'A'
'B'
'C'
I now need to create a new (numeric,double) variable D, so that D = A + B + C.
How can I get from the list of variables in the cell array, Find_Target_Vars, to adding the actual listed variables together?
Many thanks, Iain

 Accepted Answer

This is one of the (rare) cases EVAL comes in handy.
evalStr = sprintf('%s+', Find_Target_Vars{:}) ;
evalStr = evalStr(1:end-1) ; % remove trailing +
D = eval(evalStr)
Jos

5 Comments

But a necessary evil? These seems one of the few times that eval is truly needed!
Depends how A, B and C were generated...if a cell array of a struct were unavailable then probably eval is the only way.
That works perfectly, thank you! On this occasion I'm more than happy to use Evil for good...
If eval is the answer, then you are probably asking the wrong question.
If you are having to examine the workspace to figure out what variables are there, then you are probably doing something that there are better ways to do -- something like having used load() to poof variables into the workspace.

Sign in to comment.

More Answers (0)

Asked:

on 18 Feb 2011

Community Treasure Hunt

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

Start Hunting!