Creating a function that does the same as myrandperm(n,k)

I have to create a function,which does the same as myrandperm(n,k). I thought of creating a for loop which goes from 1 to k in which an array p(i) gets initialised by a random integer of an array n. And then p(i) gets deleted from from the array n.
But I didnt found a function that gives me a random integer from an array.
Do you guys have any ideas?

 Risposta accettata

randi(length(n))

4 Commenti

Hello Walter,
that does not work because length just returns the number of elements.
For example:
I have an array like d=[1 5 7 9 ] ,
I want to take randomly a number from it. For example in the first attempt I take 5. And then 5 gets deleted from that array.
In the second attempt I have to take a random number from [1 7 9]
Why can't you use randperm? It sounds like it does exactly what you need.
random index = randi(length(d))
random value = d(random index)
delete entry "random index" from d
lathe, rinse, repeat
@Rik ,because our professor does not want it, as a challenge for us.
@Walter thank you

Accedi per commentare.

Più risposte (0)

Categorie

Community Treasure Hunt

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

Start Hunting!

Translated by