0

What is the usual way in MATLAB to read an integer into an array, digit by digit?

I'm trying to split a four digit integer, 1234 into an array [1 2 3 4].

2
  • 1
    Is 1234 a numeric value (like the body of the question suggests) or a string (char, like the title suggests)? Commented Feb 15, 2013 at 13:00
  • @tmpearce - It can actually be either, but for now I am more interested in the case where it is a numeric value. Sorry about the title confusion. Commented Feb 15, 2013 at 23:46

4 Answers 4

5

Here is a very easy way to do it for a single integer

s = num2str(1234)
for t=length(s):-1:1
   result(t) = str2num(s(t));
end

The most compact way however, would be:

'1234'-'0'
Sign up to request clarification or add additional context in comments.

4 Comments

@Dan This uses the fact that character codes are ordered in the same way as numbers. So the character code of '1' is exactly 1 higher than the character code of '0'. Try '0' + 0 to find out what the codes actually are.
right I see, excellent solution. Why even bother to post the loop?
@Dan As the loop can be generalized more easily. With this method it is not so hard to produce [12 23 34 41] for example.
Note: for a matrix of numbers, num2str(matrix) - '0' will sorta work, but will return a bunch of columns of -16 due to the spaces in the character matrix produced with num2str
4

Or try this

result = str2num(num2str(1234)')'

1 Comment

This works, but sadly not for a matrix of values (as opposed to the vector in your example).
1

You can use arrayfun

arrayfun(@str2num, num2str(x))

Comments

0

Here is an elegant and efficient solution using a recursive function:

function d = int2dig(n)
   if n >= 10   
      d =  [int2dig(floor(n/10)),mod(n,10)];
   else
      d = n;
   end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.