Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab - converting the string ('321') to [3,2,1] [duplicate]

Possible Duplicate:
convert string to number array in matlab

I am a new Matlab user. I would like to know how to perform the above. I am completely stumped.

Your time and help is greatly appreciated, thanks in advance.

like image 359
JayDave Avatar asked Sep 03 '12 23:09

JayDave


2 Answers

A string in MatLab is just an array of characters.

You can subtract '0' to leave the value of each digit.

> '321' - '0'

ans =

     3     2     1
like image 122
Ben Voigt Avatar answered Nov 18 '22 05:11

Ben Voigt


Or, the less cryptic str2num or str2double applied to each element of the character array

arrayfun(@str2double, '321')

As a bonus, this will also return NaN for string values corresponding to non-scalars, i.e.

>> arrayfun(@str2double, '321a')

ans =

     3     2     1   NaN

Thus, for string '321a4' the following returns only the valid scalars:

b = arrayfun(@str2double, '321a4')
c = b(~isnan(b))
c =

 3     2     1     4
like image 34
gevang Avatar answered Nov 18 '22 05:11

gevang