Choosse randomly number of elements from a vector
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
Platform Compatibility
Windows macOS LinuxCategories
Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.