Improve performance on finding max values of matrix

7 views (last 30 days)
Hi everyone,
I have a performance issue with finding the maximum values of a matrix:
I have a matrix of 3D coordinates of points in the form
data=[X1 Y1 Z1, X2 Y2 Z2, ..., Xn Yn Zn]
With n over about 4.10^6
The values of X and Y are a grid, so basically I have about 3000 times the same Y values (Y1 to Y3000 are equal, Y3001-Y6000 are equal…). I want to find for each Y coordinate the maximum X coordinate. What I currently have is:
while i<length(data) %find for each Y Xmax
xmax(j)=max(data(data(:,2)==data(i,2),1));
ymax(j)= data(i,2);
i=find(data(:,2)== data(i+1,2), 1, 'last');
j=j+1;
end
This takes about 3 min to execute. Is there a better way to do this?

Accepted Answer

Daniel M
Daniel M on 23 Oct 2019
Edited: Daniel M on 23 Oct 2019
clearvars;
% create fake data
[y,x] = meshgrid(1:5);
data = [rand(size(x(:))).*x(:),y(:)].*2; % different values of x (1st col), for grouped y (2nd col)
% get unique values of y
[ymax,~,locMembersY] = unique(data(:,2));
% get max x for each y
xmax = splitapply(@(v) max(v), data(:,1), locMembersY);
  2 Comments
Jsqn
Jsqn on 24 Oct 2019
Works great. I went from 180s with my code to 0.7566s...
Thank you very much Daniel

Sign in to comment.

More Answers (0)

Categories

Find more on Spline Postprocessing in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!