how to convert string to an array or one dimension matrix?

3 views (last 30 days)
here is my Code...
bit = input('number:','s');
bi = str2mat(bit);
fprintf ('%i\n',bi(1));
fprintf ('%g\n',bi(2));
fprintf ('%g\n',bi(3));
why is matlab printing: 49 48 49
instead of 101 ?

Answers (2)

Star Strider
Star Strider on 7 May 2015
Because those are the ASCII codes for the numbers 1, 0, 1, and you are asking it to print numbers from a string input. Change it to:
fprintf ('%c\n',bi(1));
fprintf ('%c\n',bi(2));
fprintf ('%c\n',bi(3));
and it works as you want it to.

Guillaume
Guillaume on 7 May 2015
I'm not sure why you're using str2mat. In your case it's a noop.
49 is the ascii code of the '0' character, and 49 is the ascii code of the '1' character. converting a string (or character) to number returns the ascii code(s) of the string / character.
A simple way to convert a string consisting of only '0' and '1' into a matrix of 0 and 1 is to subtract the ascii code of '0' (i.e. 48) from the ascii codes of the strings (either 48 or 49):
bi = bit - '0'; % or bi = bit - 49

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!