from
nCtwo
by Simone Scaringi
All combinations of N elements taken two at the time.
|
| vec=nCtwo(dat) |
function vec=nCtwo(dat)
%NCTWO - All combinations of N elements taken two at a time.
% nCtwo(dat) where dat is a vector of length N, produces a matrix with
% N*(N-1)/2 rows and 2 columns. Each row of the result has two of the
% elements in the vector dat. Similar to the MATLAB function
% NCHOOSEK(dat,2) but much faster.
%
% See also NCHOOSEK, PERMS.
%
% Authors: Simone Scaringi{1} & Antonis Loizou{2}
% {1}School of Physics and Astronomy, University of Southampton
% {2}School of Electronics and Computer Science, University of Southampton
% Date: 28-05-2008
% E-mail: simo(at)astro.soton.ac.uk, al05r(at)ecs.soton.ac.uk
if ~isvector(dat) || isscalar(dat)
error('ERROR:nCtwo:InvalidArg1',...
'The input has to be a vector.');
else
combo=length(dat)*(length(dat)-1)/2;
arr1=zeros(1,combo);
arr2ix=zeros(1,combo);
n=length(dat);
pointold=0;
pointnu=0;
for i=1:n-1
pointold=pointnu;
pointnu=pointold+n-i;
arr1(pointold+1:pointnu)=dat(i);
arr2ix(pointold+1:pointnu)=i+1:n;
end
vec=[arr1; dat(arr2ix)]';
end
|
|
Contact us at files@mathworks.com