フィルターのクリア

Number of unique coordinates in an array

2 ビュー (過去 30 日間)
Patrick Mboma
Patrick Mboma 2022 年 8 月 19 日
コメント済み: Patrick Mboma 2022 年 8 月 19 日
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.

採用された回答

Bruno Luong
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));
  1 件のコメント
Patrick Mboma
Patrick Mboma 2022 年 8 月 19 日
YES SIR !!!
Respects and gratitude !!!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by