iAmWanteD
iAmWanteD

Reputation: 303

Converting between a number to a string without num2str

For example, input is a=5678. How do you make b='5678'? (b is a String). Not allowed to use str2num or any casting.

Is it possible to use log10? (I know how to do the reverse action). [This is how I did the opposite (from string to num):

s = input('Enter a number: ','s'); x = sum(10.^(length(s-'0')-1:-1:0).*(s-'0'));

Upvotes: 2

Views: 261

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112679

This looks like homework, so first here are some hints:

  • log10 may be useful to determine the number of digits.
  • mod can help to obtain each digit.
  • From your code for the reverse action: using successive powers of 10, as well as +'0' / -'0' to convert between digits and ASCII codes, may also be of help here.

And here's a possible approach using these hints (hover the mouse to find out):

b = char(mod(floor(a./10.^((ceil(log10(a))-1):-1:0)),10) + '0'):

Upvotes: 3

Related Questions