getcellnum.m 1.58 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
function [celnum,id,kdx]=getcellnum(npercell,ncells,celloffset,arg1,arg2)
%GETCELLNUM   gives cell number and index in cell
%
%[CELL,NUM,KDX]=GETCELLNUM(NPERCELL,NCELLS,CELLOFFSET,IDX) returns the cell
%   number and the index in cell of the IDX'th elements of a vector of
%   length NCELLS*NPERCELL, starting at the beginning of cell CELLOFFSET+1
%
%  NPERCELL:    Number of elements per cell
%  NCELLS:      Total number of cells
%  CELLOFFSET:  Number of cells to skip
%  IDX:         vector of indexes in the range (1..NCELLS*NPERCELL)
%               starting in cell CELLOFFSET+1
%
%[CELL,NUM,KDX]=GETCELLNUM(NPERCELL,NCELLS,CELLOFFSET,MASK)
%
%  MASK:        logical mask length NCELLS*NPERCELL
%
%[CELL,NUM,KDX]=GETCELLNUM(NPERCELL,NCELLS,CELLOFFSET,[CELL NUM])
%[CELL,NUM,KDX]=GETCELLNUM(NPERCELL,NCELLS,CELLOFFSET,CELL,NUM])
%
%See also: GETMASK, GETINDEX

if islogical(arg1)          % Logical mask
    arg1=find(arg1(:));
end
npc=zeros(1,ncells);
npc(:)=reshape(npercell,[],1);
coff=[0 cumsum(npc)];
if nargin >= 5              % cell, id
    celnum=zeros(max([size(arg1);size(arg2)]));
    id=celnum;
    celnum(:)=arg1;
    id(:)=arg2;
    kdx=reshape(coff(mod(celnum-celloffset-1,32)+1),size(celnum))+id;
elseif size(arg1,2) == 2    % [cell id]
    id=arg1(:,2);
    celnum=arg1(:,1);
    kdx=reshape(coff(mod(celnum-celloffset-1,32)+1),size(celnum))+id;
else                        % idx
    idx=arg1;
    cid=arrayfun(@(id) find(coff(2:end)>=id,1),idx)-1;
    id=idx-reshape(coff(cid+1),size(idx));
    celnum=mod(cid+celloffset,ncells)+1;
    kdx=mod(idx+coff(celloffset+1)-1,sum(npc))+1;
end
end