help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: S: random permutation


From: Ted Harding
Subject: Re: S: random permutation
Date: Mon, 14 Apr 1997 11:48:10 +0100 (GMT+0100)

( Re Message From: Dr. G. Buerger )
> 
> Hi octave,
> 
> I need a function p=f(n) such that p contains a random permutaion of the 
> first n
> natural numbers.
> 
> Any help?
> 
>       Gerd

The following function does what you want (and more): in fact the two
commands

    q = rand(n,1);
    [p,inx] = sort(q);

do what you want, the result being in "inx".

All the best,
Ted.                                    (address@hidden)
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
function [new,inx] = shuffle(old)
%
% function [New, Inx] = shuffle(Old)
%
% takes the rows of a matrix Old and shuffles them at random,
% to produce a matrix New. (If Old is a row-vector, then so is New,
% being a random permutation of the elements of Old; so also is Inx).
%
% The vector Inx contains the random permutation of 1...n such that
% Old(Inx,:) = New.
%
  rand("uniform");
  [r,c] = size(old);
  if r==1, old=old'; is_row=1 ; else is_row=0; endif
  n = rows(old); 
  q = rand(n,1);
  [p,inx] = sort(q); new = old(inx,:);
  if is_row, new=new'; inx=inx'; endif
endfunction

reply via email to

[Prev in Thread] Current Thread [Next in Thread]