Calculating binary progression using for loop

How to correct folowing- I am using for loop.
%Find open nozzles from binary data
%Binary no=sum(2^nozzle no.) --- e.g. 2^2+2^5+2^6=100
%We need to reverse calculate nozzle nos from binary pattern.
% e.g. When we enter 100, output should be 2, 5, 6.
clc
N=1:12;
for i = 1:12
a(i)=2^i;
end
T=table(N(:),a(:),'VariableNames', {'Nozzle_number', 'binarycode'});
T1=table(0,1,'VariableNames', {'Nozzle_number','binarycode'});
Tout=[T1;T]
numin=1064;
for j=1:N
n(j)=floor(log(j)/log(2));
j=j-(2^n(j));
end
T2=table(j(:),n(:),'VariableNames',{'binary','Nozzle_numbers'})
Expected answer is table of nozzle no. in this case (1064)- 10, 5, 3 (i.e. 2^10+2^5+2^3)

2 Commenti

KALYAN ACHARJYA
KALYAN ACHARJYA il 5 Lug 2019
Modificato: KALYAN ACHARJYA il 5 Lug 2019
"Expected answer is table of nozzle no. in this case (1064)- 10, 5, 3 (i.e. 2^10+2^5+2^3)"
Can you elaboate?
Or what exactly you are looking for? What are the inputs you have?
Input is a number (numin) in example it is 1064.
=1064
I am looking to calculate all power of two required to form this no. in a binary series.

Accedi per commentare.

 Risposta accettata

"Input is a number (numin), I am looking to calculate all power of two required to form this no. in a binary series"
Easily done:
numin = 1064
find(fliplr(dec2bin(numin)) == '1') - 1

2 Commenti

+1 slight variation:
>> find(fliplr(dec2bin(1064))-'0')-1
ans =
3 5 10
This helps. Thanks a lot.

Accedi per commentare.

Più risposte (1)

KALYAN ACHARJYA
KALYAN ACHARJYA il 5 Lug 2019
Modificato: KALYAN ACHARJYA il 5 Lug 2019
num=1064;
j=1;r=[];
bin_num=str2num(dec2bin(num));
num_array=num2str(bin_num)-'0';
for i=length(num_array):-1:1
if num_array(j)==1
r(j)=(i-1);
end
j=j+1;
end
disp('The 2 power are');
disp(nonzeros(r));
Result:
The 2 power are
10
5
3
Please note, three might be more easier way

Prodotti

Release

R2019a

Tag

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by