Matt
Matt

Reputation: 157

How to convert a binary row vector to a normal row vector in Matlab?

I have a binary row vector e.g.

b = dec2bin(15)

This vector behaves badly when I try to multiply it component-wise with a 'normal' vector. How do I convert b to a normal vector?

To be more specific, if

d = [1 2 3 4]

I want

n = d.*b

to give me [1 2 3 4], but it instead gives [49 98 147 196].

Thanks

Upvotes: 0

Views: 831

Answers (3)

Castilho
Castilho

Reputation: 3187

The problem is that dec2bin returns a string, not a number vector. You have to convert the char array to a numeric array, and you could do that with arrayfun, like this:

b = dec2bin(15);
b_numeric = arrayfun(@(x) str2num(x), b);
n = d.*b_numeric;

If you have the communications system toolbox, you already have a function that does exactly that, the de2bin

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283763

str2num will work, but since you're guaranteed just a single digit in each cell, you can try

b = dec2bin(15) - 48;

which should be much faster.

Note: 48 is the ASCII code for the character "0".

Upvotes: 5

High Performance Mark
High Performance Mark

Reputation: 78354

The problem you have is that dec2bin returns an array of characters. When you perform the element-wise multiplication by your array d you get the results of multiplying d element-wise by the ASCII code for the character '1', which is 49.

If you want to multiply d by the array [1 1 1 1] this seems like a convoluted approach. So what are you really trying to do ?

To convert a character (array) to a number you would use the str2num function. Here it would convert the string '1111' to the number 1111 so str2num(dec2bin(15)) returns 1111.

Upvotes: 2

Related Questions