MATLAB: Collect double values of a matrix

loopMATLABmatrix

Hi,
I have got a question. I have a matrix with three columns (X,Y,Z coordinates) and nearly 60000 rows. Now, I would like to compare the X and Z values of all 60000 rows. All rows whose X and Z values only occur once should be deleted, only the rows whose X and Z value occur twice or more should be regarded. Next, the rows with the equal X and Z value should be compared and the row with the higher Y value should be written into a new matrix.
I thought about using a loop for the search of the rows with equal X and Z values but the computing time is quite high, is there a better way? And how do I define the "do"?
for k = 1:end
for m = k+1:end
if A(k,1) == A(m,1) && A(k,3) ==A(m,3)
do something
end
end
end
I haven't thought about the loop for the search of the higher Y value, yet.
Yours,
Tobias

Best Answer

Let xyz - your array (n x 3);
[~,~,c] = unique(xyz(:,[1,3]),'rows','stable'); % c - serial numbers of rows with same values in first and last columns.
d = accumarray(c,1); % d - the number of specific rows with the same first and last columns. Here first row of 'd' c = 1, nth row - c = n.
[lo,i] = ismember(c,find(d > 1)); % duplicate rows in xyz.
j = accumarray(i(lo),find(lo),[],@(x)x(max(xyz(x,2)) == xyz(x,2))); % index of the row with the maximum value in the second column.
out = xyz(j,:);