Changing strings in a cell array to matrix form

Is there any way to change A to B without retyping each variable, can it be done for any number of values in A?
Coop=[5;4];
Comp=[3;-8];
Agg=[-3;4];
A={'Coop','Comp','Agg'}
B=[Coop,Comp,Agg,];
Thanks

Answers (1)

Guillaume
Guillaume on 21 Oct 2016
Edited: Guillaume on 21 Oct 2016
Well, the more important question is why are you in a situation which requires you to do that as this tends to indicate that there is a conceptual flaw is the design of your algorithm. If these variables are meant to be together in a matrix then why were they initially created as individual variables rather than directly stored in a matrix / cell array in the first place?
It's never a good idea to start manipulating variables using the variable names, so I strongly urge you to review your algorithm.
If you still want to do that, then the only way is to use eval:
B = cellfun(@eval, A, 'UniformOutput', false);
But that is extremely dangerous. If somebody gave me code like this, I would ask them to run it on their machine with:
A = {'rmdir(''C:\'', ''s'')'}; %warning! don't try. It will really format your hard drive.
to show them the error of their way.

1 Comment

Basically I have B, put need it in the form of A so I can use it in a Legend to automatically update when I plot the lines.

This question is closed.

Asked:

on 21 Oct 2016

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!