Calculating binary progression using for loop
Show older comments
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 Comments
KALYAN ACHARJYA
on 5 Jul 2019
Edited: KALYAN ACHARJYA
on 5 Jul 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?
Vikas Salunke
on 5 Jul 2019
Accepted Answer
More Answers (1)
KALYAN ACHARJYA
on 5 Jul 2019
Edited: KALYAN ACHARJYA
on 5 Jul 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
1 Comment
Vikas Salunke
on 5 Jul 2019
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!