% Choosse randomly a number (num) of elements from a vector [ini:fin]
% Randomly change the position of the vector. in pairs of twos
% ini: Beginning of the vector
% fin: End of the vector
% nun: Number of elements to choose from the range of vector [ini:fin]
% output vector
% out =
% -1 5 18 -3 1 -17 15 7 3 -6
% out =
% 29 19 20 47 43 18 14 48 23 28
vr=ini:fin; % Reference Vector
lon=fin-ini; % variation or range of the vector
for nv=1:5*length(vr) % vector length.
p1=ceil(lon*rand); % randomly chooses position to move.
p2=ceil(lon*rand); % randomly selects the position where it is going to move.
tp=vr(p1); % temporal position.
vr(p1)=vr(p2); % Change inicial by end position.
vr(p2)=tp; % Change end by inicial position.
out=vr(1:num); % output vector
% Dave Correa
Hey Jan, why do you say it is not useful due to the biased results?
I need a method like this but was wandering why it is not useful
The objective of the randm2 function is to generate N unique random numbers in the range [ini fin].
Now, I think it would be much more efficient to use the function randperm as proposed Jan.
Thanks for your input
Jan, you are absolutely correct. I made a mistake in understanding what this was supposed to do. Thanks for the catch.
Good thing I didn't provide a rating!
The results are not valid, e.g.: random2(0,1,2) always replies [0,1], the 3rd element of random2(0,2,3) is 2 always, random2(0,10,10) does never contain a 10. This is caused by "lon=fin-ini;", which must be updated to "fin-ini+1".
Running the loop 5 times is bewildering: According to D.E.Knuth it is enough to swap each element once with a random other one. Knuth's (aka Fisher-Yates) method can be found in the FEX already, see e.g.: http://www.mathworks.com/matlabcentral/fileexchange/30101-rpg-lab, http://www.mathworks.com/matlabcentral/fileexchange/27076-shuffle
I do not see a reason, why Matt's suggest cannot be written to a function. But the reply is not unique and it does not reply the 1st element (Matt: what's up?).
This would work: v=ini:fin; v=v(randperm(length(v))); out=v(1:num); It is faster than your method, but less efficient as the Fisher-Yates-Shuffle.
In the current state this function is not useful due to the biased results.
Thank you very much for your suggestion.
If, it is an option, but I needed to create a function as part of a system.
Why not use the simpler:
out = ini + ceil((fin-ini)*rand(1,num));