Choosse randomly number of elements from a vector

Choosse randomly a number of elements from a vector. Randomly change the position of the vector
266 Downloads
Updated 30 Jun 2011

View License

function [out]=random2(ini,fin,num)
% Choosse randomly a number (num) of elements from a vector [ini:fin]
% Randomly change the position of the vector. in pairs of twos
%
% Imput:
% ini: Beginning of the vector
% fin: End of the vector
% nun: Number of elements to choose from the range of vector [ini:fin]
%
% Output
% output vector
%
% Example
%
% [out]=random2(-20,20,10)
%
% out =
% -1 5 18 -3 1 -17 15 7 3 -6
%
% [out]=random2(5,50,10)
%
% 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.
end

out=vr(1:num); % output vector

% contact:
% Dave Correa
% correa.dave30@gmail.com
% http://fismatlab.blogspot.com

Cite As

Dave Correa (2024). Choosse randomly number of elements from a vector (https://www.mathworks.com/matlabcentral/fileexchange/32017-choosse-randomly-number-of-elements-from-a-vector), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2010a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes
1.2.0.0

update link

1.0.0.0