Number of unique coordinates in an array
1 次查看(过去 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!