Say I have a row vector in Matlab called C
|dw:1354849974079:dw|
I need to add all the 1's together, so 512+256+128+64+16+8+4+2
Do you have a 2x12 matrix with both of these data? Or are they separate vectors?
It's just a seperate matrix 12 x 1
only binary values.
Use a for loop to go through each binary number in your vector C. Then convert it to decimal and add it to a total sum. Give me a sec and I'll try it out and share the code
Alright
there is no decimal places in the binary number right?
no
Just 1s and 0s if that's what you mean.
Also, it turns out the Vector is a column vector, not row
so 1 x 12
cool. now do you know how to convert binary to decimal? It's just: given a1, a2, a3, a4 (the numbers that make up a binary number) It's decimal equivalent is: (a1)(2^3) + (a2)(2^2) + (a3)(2^2)
it's easy to convert between row and collumn vectors with transpose()
Can I use the function v = bi2de(b); where b is the vector?
haha, didn't even know that existed. And yes you can I just tried it and it certainly works. ..and I almost had it too:(
but you have to use transpose() first to convert it into a row vector
This appears to work. Try it yourself. It gives me 990 as the total clc; clear all; a=[0 0 1 1 1 1 0 1 1 1 1 0]; b=[2048 1024 512 256 128 64 32 16 8 4 2 1]; ttl=0; for n=1:12 if(bi2de(a(n)))==1 ttl=ttl+b(n) end end
hmm, I guess you need that because it doesn't seem to work when you have leading zeroes oddly
Just use this: function [accum] = binaryConverter(C) accum = 0; for i = 1:(length(C)) decimalPlace = length(C) - i; accum = accum + C(i)*2.^(decimalPlace); end end
Because matlab indices start from left to right but you need to count decimal places from right to left. That is why there is separate i and decimalPlace variables
you can also use fliplr() It flips a vector left to right at once.
cool, that will surely come in handy. But using that here you still end up have one variable counting the opposite way of the other
Is function an invalid variable?
if you're incorporating this into something else just use: accum = 0; for i = 1:(length(C)) decimalPlace = length(C) - i; accum = accum + C(i)*2.^(decimalPlace); end since in matlab .m files can be either functions or scripts
using this you're assuming C has already been made and accum is your result. This method removes the need for that extra vector of powers of 2.
So, v is the vector that has these binary numbers
is that what is it supposed to be? Ifso, given v = [0, 0, 1, 1, 1....] accum = 0; for i = 1:(length(v)) decimalPlace = length(v) - i; accum = accum + v(i)*2.^(decimalPlace); end and accum will be your answer(a 1x1 scalar matrix) (Since everything in matlab is a matrix)
ok, It work perfectly.
congrats, matlab rocks, also EE ftw!
Thanks!!!
Join our real-time social learning platform and learn together with your friends!