Starting with a matrix M
of particle counts, this will get you a mask in Mb
of the boundary as it has been defined by the question,
% define particle count matrix and find non-zero locations
M = randi(5,10,10)-1
[nr,nc] = size(M);
[pRows,pCols] = find(M);
% identify locations that compose the "boundary" line
boundCoords = [accumarray(pCols,pRows',[nc 1],@min)', ...
accumarray(pCols,pRows',[nc 1],@max)', ...
1:nr 1:nr; ...
1:nc 1:nc, ...
accumarray(pRows,pCols',[nr 1],@min)', ...
accumarray(pRows,pCols',[nr 1],@max)'];
boundCoords = unique(boundCoords','rows');
boundCoords(any(boundCoords==0,2),:)=[]; %' remove possible (unlikely) zeros
% create a mask representation of the boundary line
Mb = false(size(M));
Mb(sub2ind(size(Mb),boundCoords(:,1),boundCoords(:,2))) = true
That is what I understand you want your boundary mask to look like. The number of pixels that make up the boundary is
numBorderPix = sum(Mb(:))
The number of particles on those border points is then
numBorderParticles = sum(M(Mb))
NOTE: This solution will ensure that each point on the boundary line has a non-zero particle count.