MATLAB create a converter function (input: whole number) (output: string)

조회 수: 2 (최근 30일)
Sang Yeob Kim
Sang Yeob Kim 2014년 12월 4일
답변: Star Strider 2014년 12월 4일
In MATLAB, I want to create a function that takes input a whole number and output a string without using built-in functions such as num2str, int2str, or mat2str. The whole number can possibly with a leading minus sign. Please help!

답변 (2개)

Peter
Peter 2014년 12월 4일
You can use:
if (n < 0)
signstr = '-';
n = abs(n);
elseif (n == 0)
signstr = '0';
else
signstr = '';
end
str = '';
while n > 0
d = mod(n,10);
str = [char(d+48), str];
n = floor(n/10);
end
str = [signstr, str];
Or if you don't want to use the char() function, replace that line with a switch statement:
switch d
case 0, str = ['0', str];
case 1, str = ['1', str];
case 2, str = ['2', str];
case 3, str = ['3', str];
case 4, str = ['4', str];
case 5, str = ['5', str];
case 6, str = ['6', str];
case 7, str = ['7', str];
case 8, str = ['8', str];
case 9, str = ['9', str];
end

Star Strider
Star Strider 2014년 12월 4일
Another way:
x = -fix(pi*1E+5); % Input Integer
ns = int8(sign(x));
n = abs(x);
prec = ceil(log10(n));
for k1 = prec:-1:1
d(k1) = fix(rem(n,10));
n = n/10;
end
ascii0 = uint8('0');
out = char(uint8(d)+ascii0);
if ns==-1
out = ['-' out];
end
produces:
out =
-314159

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by