Number of unique coordinates in an array
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Patrick Mboma
le 19 Août 2022
Commenté : Patrick Mboma
le 19 Août 2022
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 commentaires
Réponse acceptée
Bruno Luong
le 19 Août 2022
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));
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!