JDS
JDS

Reputation: 17008

MATLAB convert string representing array to actual array?

I have the following:

ans = 

    '[-1, 0, 1, 0, 0, 0]'

I really want the variable

x = [-1, 0, 1, 0, 0, 0]

How can I convert ans into x?

Upvotes: 1

Views: 274

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112769

Use str2num:

s = '[-1, 0, 1, 0, 0, 0]';
x = str2num(s);

If your input is a cell array:

c = {'[-1, 0, 1, 0, 0, 0]'};
x = str2num(c{1});

Upvotes: 3

Bruce Dean
Bruce Dean

Reputation: 2828

Try this:

a =  '[-1, 0, 1, 0, 0, 0]'

x = str2num(a(2:end-1))

Upvotes: 2

Related Questions