# find max of every 4 rows in a matrix and save in separate array

1 view (last 30 days)
Edited: Hariprasad on 18 Apr 2016
Im trying to find max of 5th column of every 4 rows in a matrix say A. I need to push the max rows into a separate matrix B and remove these rows from A. I have attached sample data herewith. The data is for 6 customers with 4 tags(12,22,32,42) for each customer. I need to take the max of percentage between the four tags for each customer. So far I have tried with a for loop as :
custs = unique(data(:,3));
highertrp = zeros(size(custs,1),1);
for i = 1 : size(custs,1)
idx = find(data(:,3)== custs(i,1));
[~,id] = max(data(idx,5),[],1);
highertrp(i,1:size(data,2)) = data(idx(id),:);
data(idx(id),:) = [];
end
But this is too slow as I can have about 1 million records to check in my project. Any help will be great.

Andrei Bobrov on 18 Apr 2016
Edited: Andrei Bobrov on 18 Apr 2016
[~,~,c] = unique(data(:,3));
idx = accumarray(c,(1:size(data,1))',[], @(x) x( max(data(x,5))==data(x,5) ,:) );
highertrp = data(idx,:);
data(idx,:) = [];
in case if find max of every 4 rows
[~,ii] = max(reshape(data(:,5),4,[]));
idx = ii + (0:numel(ii)-1)*4;
highertrp = data(idx,:);
data(idx,:) = [];
Oh ok the indices of each Id. Thank you @Andrei Bobrov