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 Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by