Can this code be more efficient?

조회 수: 4 (최근 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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by