Sorting a vector with another vector of multiple maximums
1 次查看(过去 30 天)
显示 更早的评论
Hi,
I have a function that I want to compute a queue "Qevents", which gets information from a set of points "P" (columns x and y) and sorts them by maximum y value. If there are other (same) maximum y values, I want to store the maximum y-value that has the largest corresponding x value. As the code is executed, points are deleted from the original data set so a new maximum can be examined. I have started writing out the code to this:
% given a list of points P(n,2) representing x,y coordinates
for i=1:length(P)
indx = P==max(P(:,2)); % find index of maximum in set of points..
if "multiple maximums" % don't know the code for this line
if indx(i,1)==1 && indx(i,2)==1 % checks for maximums in both columns
Qevents(i) = max(P(:,2)); % stores maximum y-value recursively
P(i,:) = []; % and removes it from the list of points
end
else
Qevents(i) = max(P(:,2))
P(indx) = [];
end
end
I have no idea how to check for multiple maximums and use it in a loop properly. Any help would be appreciated. Thanks!
Ian
0 个评论
采纳的回答
kjetil87
2013-8-14
编辑:kjetil87
2013-8-14
Im not a 100% sure if this is what you are asking for, but as for checking for multiple maximums you are actually already doing this.
Example:
%here test(:,2) has two max values.
test=[1,2;...
2,3;...
3,3];
indx=test(:,2)==max(test(:,2))
indx =
0
1
1
index now holds true if test(:,2) is the maximum value. if there are more then 1 true element in indx , it means that there are several maxima so to test for this simply use :
if nnz(indx)>1
to check for the maximum x value (i assume this is test(:,1) ) you do the same exercise but use logical indexing to sort out the possible candidates:
indxX=test(:,1)==max(test(indx,1));%i assume that x values cannot be equal
indxX now holds the index for the row containing maximum value of both x and y.
so Qevents(i)=test(indxX,2);
Another more readable solution would be to use sort and find.
test=[1,2;...
3,3;...
2,3]; % i now made sure that the x values are not sorted.
% sort the array with respect to x values.
[~,idx]=sort(test(:,1));
test=test(idx,1:2); % remember to also switch around the y values.
Then you can use find(..) to get the last maximum y value (since x is now sorted)
indx=find(test(:,2)==max(test(:,2)),1,'last');
Note that index is now a scalar index and not a logical vector. But still the value you are looking for is:
test(indx,2);
Play around with the two methods see which one fits you best =)
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!