V_SORT Sort in ascending or descending order including an inverse index. This routine performes the same function as sort but includes an additional output, j, which is the same size as b and i and gives an inverse index . If the input is a column vector, a, then b=a(i) and a=b(j). The routine does not currently accept the "dim" argument to sort and the first argument must be a vector or matrix.
0001 function [b,i,j]=v_sort(varargin) 0002 %V_SORT Sort in ascending or descending order including an inverse index. 0003 % 0004 % This routine performes the same function as sort but includes an additional 0005 % output, j, which is the same size as b and i and gives an inverse index . 0006 % If the input is a column vector, a, then b=a(i) and a=b(j). 0007 % 0008 % The routine does not currently accept the "dim" argument to sort and the 0009 % first argument must be a vector or matrix. 0010 % 0011 0012 % Copyright (C) Mike Brookes 2023 0013 % 0014 % VOICEBOX is a MATLAB toolbox for speech processing. 0015 % Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html 0016 % 0017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 0018 % This program is free software; you can redistribute it and/or modify 0019 % it under the terms of the GNU General Public License as published by 0020 % the Free Software Foundation; either version 2 of the License, or 0021 % (at your option) any later version. 0022 % 0023 % This program is distributed in the hope that it will be useful, 0024 % but WITHOUT ANY WARRANTY; without even the implied warranty of 0025 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 0026 % GNU General Public License for more details. 0027 % 0028 % You can obtain a copy of the GNU General Public License from 0029 % http://www.gnu.org/copyleft/gpl.html or by writing to 0030 % Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA. 0031 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 0032 % 0033 [b,i]=sort(varargin{:}); 0034 if nargout>2 0035 if nargin>1 && isnumeric(varargin{2}) || ndims(b)>2 0036 error('The dim input is not supported and the input must be a vector or matrix'); 0037 else 0038 [r,c]=size(i); 0039 j=zeros(r,c); 0040 if r==1 && c>1 % if a row vector 0041 j(i)=1:c; 0042 else 0043 k=i+repmat(0:r:r*(c-1),r,1); 0044 j(k(:))=repmat((1:r)',c,1); 0045 end 0046 end 0047 end