Looping through data and finding maximum value in each bin

4 次查看(过去 30 天)
I have a dataset:
ds = BIN VALUE ID
10 5 1
10 6 2
11 3 2
11 7 1
11 4 1
Bins are unique. I need to find the ID with the maximum VALUE for each BIN. Example output in the above example:
MAX = BIN VALUE ID
10 6 2
11 7 1
This was my attempt to loop through the data producing output where each column is a BIN and the row contain the VALUES. I was then going to find the maximum of each bin (column) but the values didn't sort right.
bin = unique(ds(:,1));
val = ds(:,2);
b=numel(bin);
a=cell(b,1);
for i=1:b
a{i}=ds(ds(:,1)==idate(i),2:3);
for j=1:length(a{i})
output(j,i)=(a{i}(j));
end
end
I'm probably over complicating this. I have Matlab 2011. Thanks in advance for your time!

采纳的回答

Andrei Bobrov
Andrei Bobrov 2013-8-21
ds = [...
10 5 1
10 6 2
11 3 2
11 7 1
11 4 1 ];
d1 = sortrows(ds,[1 2]);
[~,ii] = unique(d1(:,1));
out = d1(ii,:);

更多回答(2 个)

David Sanchez
David Sanchez 2013-8-21
You could try something like this:
ds = [ 10 5 1 ;
10 6 2 ;
11 3 2 ;
11 7 1 ;
11 4 1 ];
sorted = sort(ds,1)
sorted =
10 3 1
10 4 1
11 5 1
11 6 2
11 7 2
max_val = sorted(end,:)
max_val =
11 7 2

Azzi Abdelmalek
Azzi Abdelmalek 2013-8-21
编辑:Azzi Abdelmalek 2013-8-21
v=[10 5 1
10 6 2
11 3 2
11 7 1
11 4 1]
[c1,ii,jj]=unique(v(:,1),'stable')
c2=accumarray(jj,v(:,2),[],@max)
m=[c1 c2]
out=v(all(ismember(v(:,1:2),m),2),:)
out=unique(out,'rows','stable')

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by