Can this code be more efficient?
5 ビュー (過去 30 日間)
古いコメントを表示
I wrote this code with some help of a classmate and I think the code can run more efficiently. It coverts whole numbers & numbers between 0 & 1 to binary numbers. Any help is appreciated.
n=input('Enter a positive value: ');
i=n; j=1; k=1; stop=0; binary=0; binaryStr='0';
if n>=1 || n==0
% i=n; j=1;
% binary=0;
% binaryStr='0';
while i>=1
binary(j)=rem(i,2);
i=floor(i/2);
j=j+1;
end
%disp(binary);
binary=fliplr(binary);
%converting the binary vector to type string:
for k=1:length(binary)
binaryStr(k)=num2str(binary(k));
end
% disp(binaryStr);
elseif n>0 & n<1;
while i~=1
if stop==1
break; %break the main while-loop
end
i=i-floor(i); %subtracts the lead integer, 1 or 0, from the decimal.
value(j)=i;
while j>=2 && k<j %a loop that compares i to all previous values of i
if value(k)==value(j)
stop=1; %a value to break the main loop.
break %breaks this inner while-loop
end
k=k+1;
end %end of comparison loop
i=i*2;
binary(j)=floor(i);
j=j+1;
k=1;
end
for k=1:length(binary)
binaryStr(k)=num2str(binary(k));
end
binaryStr=strcat('.',binaryStr); %adds '.' to the front of binaryStr
end
disp(binaryStr);
0 件のコメント
回答 (1 件)
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!