2

How to create numeric array from a string in Matlab?

For example I have such a string:

>> str = dec2bin(7);
s = 111

I need the array [1 1 1]. How to do it?

I see strread function strread but I get difficulties to use it with non-space string input.

Larry Foobar
  • 11,092
  • 15
  • 56
  • 89

5 Answers5

2

Just answered another question and found a part of it might be useful here.

You can actually convert such a string to a logical vector:

a = str == '1';

You can cast it to another type, for example double(a).

Community
  • 1
  • 1
yuk
  • 19,098
  • 13
  • 68
  • 99
2

The standard solution is to use the solution posted by yuk,

a = (str == '1');

which produces a logical result. If you need a double,

a = double(str == '1');

or even just:

a = +(str == '1');

Perhaps the simplest looking solution is this one:

a = str - 48;

although I think the last is least obvious as to what it does. I prefer code that is easy to read and understand the purpose. That goal is best met by the second solution, IMHO.

1

I suppose, naively:

n = length(s);
myArray = zeros(1,n)
for i = 1:n
myArray(i) = double(s(i));

where "double()" is whatever the command is for changing a string element to a double precision number, if that is indeed what you want.

clustro
  • 11
  • 2
1

The answer is using "bitget"

> x = bitget(7,1:3);

> class(bitget(7,1:3))  
  ans =  

  double

The result is double.

yuk
  • 19,098
  • 13
  • 68
  • 99
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
1

With strread: a = strread('123', '%c')

Clement J.
  • 3,012
  • 26
  • 29