Can this code be more efficient?

4 次查看(过去 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);

回答(1 个)

Walter Roberson
Walter Roberson 2015-7-11
For one thing you should look at dec2bin()

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by