Number of unique coordinates in an array
조회 수: 3 (최근 30일)
이전 댓글 표시
Dear all,
I am trying to solve the following problem as fast as possible. Consider a square matrix with coordinates (i,j) where i denotes the row and j the column. I would like to write a function that returns the number of unique elements for every coordinate pair. For instance, for a pair (6,2), the number unique elements is 2, while for the pair (4,4) the number of unique elements is 1. This is just the description of the basic problem.
More generally, I would like to be able to do the same not just for a matrix but also for a cube and for higher order arrays. To that end, I wrote the following function
function [dm,relvnt]=multiplicity(nz,degree)
ndx=1:nz^degree; % index for all the elements in the array
siz=[1,repmat(nz,1,degree)]; % size of the array : vector, matrix, cube, ... etc.
[varargout{1:degree+1}] = ind2sub(siz,ndx); % locating rows, columns, pages, etc.
varargout=cellfun(@(x)x(:),varargout,'UniformOutput',false); % turning into column vectors
relvnt=cell2mat(varargout); % collapsing coordinates into a matrix
[nrows,ncols]=size(relvnt);
relvnt=mat2cell(relvnt(:,2:end),ones(1,nrows),ncols-1); % suppressing the first column and putting into a cell array
dm=cellfun(@(x)numel(unique(x)),relvnt); % counting the number of unique terms in each cell
end
This works well for any dimension nz and any degree. However, it becomes prohibitively slow as nz and degree increase. I wish I could just transform an index into the number of unique coordinates possibly in a vectorized fashion.
댓글 수: 0
채택된 답변
Bruno Luong
2022년 8월 19일
Is this what you want?
n=4; d=3;
c=cell(1,d);
[c{:}]=ndgrid(1:n);
relvnt=reshape(cat(d+1,c{:}),[],d);
dm = d-sum(diff(sort(relvnt,2),1,2)==0,2);
dm = reshape(dm,n+zeros(1,d));
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!