|
|
| sub2ind4up(I, J)
|
function IND = sub2ind4up(I, J)
%SUB2IND4UP Linear index from subscripts of upper triangular matrix (only
%elements above diagonal)
% SUB2IND4UP determines the equivalent single index corresponding to a
% given set of subscript values for a 2D upper triangular matrix,
% excluded all elements over the diagonal.
%
% IND = SUB2IND4UP(I, J) returns the linear index equivalent to the
% row and column subscripts I and J
%
% Let ind be a vector of indexes for entries of some upper triangular
% matrix. The entries are selected vertically so that:
%
% ind = 1 is associated to entry (1, 2)
% ind = 2 is associated to entry (1, 3)
% ind = 3 is associated to entry (2, 3)
% ind = 4 is associated to entry (1, 4)
% ...
% ind = N * (N - 1) / 2 is associated to entry (N - 1, N)
%
% % ======================================================================
%
% EXAMPLE
%
% % Note that if
% A = rand(10);
% % and
% b = A(find(triu(A, 1)));
% % then, given subscripts
% I = [1:9];
% % and
% J = [2:10];
% % for matrix A, these are equivalent to indices
% IND = sub2ind4up(I, J);
% % for vector b. In fact:
% all(A(sub2ind(size(A), I, J)) == b(IND)')
%
% % ans =
% % 1
%
% % This is obtained without even knowing about size(A)
%
% % ======================================================================
%
% See also SUB2IND, IND2SUB, FIND.
%
% % ======================================================================
%
% Author: Francesco Pozzi
% E-mail: francesco.pozzi@anu.edu.au
% Date: 1 May 2010
%
% % ======================================================================
%
% Check input
ctrl1 = isnumeric(I) & isreal(I) & isnumeric(J) & isreal(J);
if ctrl1
I = I(:);
J = J(:);
ctrl2 = ~any(isnan(I)) & ~any(isinf(I)) & all(I > 0) & ~any(isnan(J)) & ~any(isinf(J)) & all(J > 0);
if ~ctrl2
error('Check indexes: they need to be positive integers!')
else
ctrl3 = all(I < J);
if ~ctrl3
error('Check indexes: in an upper triangular matrix row indexes need to be less than column indexes!')
end
end
else
error('Check indexes: they need to be positive integers!')
end
IND = round(J .* (J - 3) / 2 + I + 1);
|
|
Contact us