rameezk
rameezk

Reputation: 353

Converting a string value (array of char's) to a matrix in Matlab

So basically this is what I want to do:

I have the decimal value 3 as such:

x=3

Now i get the binary format as such:

s = dec2bin(x,3)
s = 011

The format of s is a string (correct?).

Now I would like to convert this value to a matrix, in order to do matrix operations on it. As such:

A = [0 1 1]

But I cannot seem to get this right. I have tried both str2mat and cell2mat but no results. Any ideas?

Upvotes: 0

Views: 3209

Answers (3)

Castim
Castim

Reputation: 125

You can as well do that:

x=3;
binNumber = dec2bin(x,3);
A=sprintf('%s',binNumber) - '0';

Upvotes: 0

Smash
Smash

Reputation: 3802

If you are 100% certain you will only be getting 0s and 1s, use:

a = '001';
b = double(a)-48;

(0 is 48 in ASCII)

Upvotes: 2

John Colby
John Colby

Reputation: 22588

Here's one way:

>> cellfun(@str2num, cellstr(s'))'

ans =

     0     1     1

As you've noticed, MATLAB isn't that great for string manipulation. :)

Upvotes: 0

Related Questions