How to create a function that returns a matrix with one more popped piece randomly added and the location of it.

2 visualizzazioni (ultimi 30 giorni)
Hi there, 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
This is a homework question so a nudge in the right direction would be greatly appreciated!

Risposta accettata

Roger Stafford
Roger Stafford il 25 Gen 2015
Use 'randi' twice to generate random indices for the row and column and then add 1 there.
  7 Commenti
Image Analyst
Image Analyst il 25 Gen 2015
You need to declare a second output argument, rowAndColumn
function [output, rowAndColumn] = popcorn(M)
Now, what do you think, looking over your variables, rowAndColumn might be?
rowAndColumn = ??????
By the way, your "b" is totally unnecessary. And even worse , it's totally wrong . It needs to be the whole matrix, not just the one element. Keep trying.
Rohan Nair
Rohan Nair il 25 Gen 2015
Okay thank you, after a lot of thinking and reading what you said this is the new code, though it only gives a 1x2 matrix and not the matrix i need as per the example: function [output, rowAndColumn] = popcorn(M) [w, z] = size(M); a = randi(w); f = randi(z); rowAndColumn = [w,z]; output = [a,f]; end
I feel I'm getting closer to the answer yet i still feel so lost.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by