PDA

View Full Version : Totally random Matlab question


thomasp
6 Sep 2009, 12:56
Yes I know this is random, but what the hell :p Have searched the Mathworks site but can't find anything.


How can I extract each digit from an integer number into an array? So for example, if x = 52, how could i get this to return an array of y = [5 2]. Or if x = 1563, y would equal [1 5 6 3] (i.e., "units" in one cell, "tens" in another, "hundreds" in another).

Any ideas?

Xinos
6 Sep 2009, 16:51
Use modulus?

int a = 0
while(x > 0)
{
y[a] = x %10
x/10
a++
}


That will be backwards though. I guess you should do the modulus thing first to find out how long the array has to be, then define the array and start putting the numbers in it in reverse.

SupSuper
6 Sep 2009, 18:23
Convert it to a string and convert it back?

y = function num2arr(x)
_temp = num2str(x);
_y = [];
_for i=1:length(temp)
__y[i] = str2num(temp[i]);
_end
end

(underscores for readibility, remove them if you use it)
Xinos' methood is probably more efficient though.

thomasp
8 Sep 2009, 16:10
Cheers for the replies :)

Used SupSuper's method in the end (without the function file) as that fitted in better with my code.


For those who care I was trying to solve a teaser question in the Sunday Times. If anyone else is bored enough and has no life, like me, here's the question for you to solve!

Geroge and Martha gave their grandson nine plastic cups, numbered 1 to 9, and 45 marbles. They asked him to place one marble in cup 1, two in cup 2, etc. A while later he had indeed used all the marbles, placing a different number in each cup, but no cup contained the correct number. The child explained the task was too easy, so, for each cup, he had multiplied its number by George and Martha's two-figure house number, added up the product's digits, looked at the units digits of that sum, and placed that number of marbles in the cup.

What is the house number?

AndrewTaylor
9 Sep 2009, 18:57
Since we're in Matlab, you could even say
y=double(sprintf('%.0f',x)-'0')
Matlab is almost designed to produce unreadable code.

Edit: I think you could do that. You might have to split it into two calls to double().