samedi 24 janvier 2015

MATLAB: How to randomly increase a random element in a matrix by one 'popping'?

I am stuck on a question and don't know how to go about it:


Write a function that given a matrix M of numbers representing locations and the number of popcorn pieces that have previously popped at each, returns a matrix with one more popped piece randomly added. In addition, the function returns the row-column coordinate where the latest piece popped.


For example:



>> a = zeros(2)
a =
0 0
0 0
>> aa = popcorn(a)
aa =
1 0
0 0
>>[aaa rc] = popcorn(aa)
aaa
2 0
0 0
rc =
1 1
>> [aaaa rc] = popcorn(aaa)
aaaa =
2 0
0 1
rc =
2 2
>>aaaaa = popcorn(aaaa)
aaaaa =
2 1
0 1

So far, what i have is:

function output = popcorn(M)
[w, z] = size(M);
a = randi(w);
f = randi(z);
b = w(a,f);
output = b;


But then i get an error saying:



Attempted to access w(1,2); index out of bounds because numel(w)=1.

Error in popcorn (line 5)
b = w(a,f);


And its here where I'm stuck, any help will be greatly appreciated!





Aucun commentaire:

Enregistrer un commentaire