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.

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

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.

Comments

1

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

Comments

1

The answer is using "bitget"

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

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

  double

The result is double.

1 Comment

Thank you very much. I don't need strings anymore ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.