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 件のコメント

KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 7 月 5 日
編集済み: KALYAN ACHARJYA 2019 年 7 月 5 日
"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
Vikas Salunke 2019 年 7 月 5 日
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.

サインインしてコメントする。

 採用された回答

Guillaume
Guillaume 2019 年 7 月 5 日

1 投票

"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 件のコメント

Stephen23
Stephen23 2019 年 7 月 5 日
編集済み: Stephen23 2019 年 7 月 5 日
+1 slight variation:
>> find(fliplr(dec2bin(1064))-'0')-1
ans =
3 5 10
Vikas Salunke
Vikas Salunke 2019 年 7 月 5 日
This helps. Thanks a lot.

サインインしてコメントする。

その他の回答 (1 件)

KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 7 月 5 日
編集済み: KALYAN ACHARJYA 2019 年 7 月 5 日

1 投票

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

カテゴリ

製品

リリース

R2019a

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by