Can this code be more efficient?

5 ビュー (過去 30 日間)
David Hughes
David Hughes 2015 年 7 月 11 日
コメント済み: Walter Roberson 2015 年 7 月 11 日
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);

回答 (1 件)

Walter Roberson
Walter Roberson 2015 年 7 月 11 日
For one thing you should look at dec2bin()
  2 件のコメント
David Hughes
David Hughes 2015 年 7 月 11 日
The purpose of the code is to not use built in matlab functions.

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by