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

2 Ansichten (letzte 30 Tage)
Sang Yeob Kim
Sang Yeob Kim am 4 Dez. 2014
Beantwortet: Star Strider am 4 Dez. 2014
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!

Antworten (2)

Peter
Peter am 4 Dez. 2014
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 am 4 Dez. 2014
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

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by