Loop For extract maximum rows of matrix based on vectors

조회 수: 1 (최근 30일)
abdullah al-dulaimi
abdullah al-dulaimi 2022년 12월 7일
답변: Fangjun Jiang 2022년 12월 7일
I have this data , Consist of 3 vectors, i want to create a Loop for 1:5: size(data) , to extract rows that have maximum value for vector 2 (colomn number 2)
1 3 4
1 5 4
1 6 4
1 2 4
1 1 4
2 4 4
2 4 4
2 4 4
2 4 4
2 5 4
1 1 4
1 1 4
1 2 4
1 3 4
1 5 4
2 5 4
2 5 4
2 5 4
2 5 4
2 6 4
The result will be
1 6 4
2 5 4
1 5 4
2 6 4
  댓글 수: 1
Walter Roberson
Walter Roberson 2022년 12월 7일
Is the rule that you want to find the maximum for each group of lines that has the same value in the first column? Even if the third column is different? Or should it be groups of lines that have the same first and third column ?

댓글을 달려면 로그인하십시오.

채택된 답변

Voss
Voss 2022년 12월 7일
data = [
1 3 4
1 5 4
1 6 4
1 2 4
1 1 4
2 4 4
2 4 4
2 4 4
2 4 4
2 5 4
1 1 4
1 1 4
1 2 4
1 3 4
1 5 4
2 5 4
2 5 4
2 5 4
2 5 4
2 6 4
];
[n_rows,n_cols] = size(data);
assert(mod(n_rows,5) == 0)
result = zeros(n_rows/5,n_cols);
for ii = 1:5:n_rows-4
temp_data = data(ii+(0:4),:);
[~,idx] = max(temp_data(:,2));
result((ii-1)/5+1,:) = temp_data(idx,:);
end
disp(result);
1 6 4 2 5 4 1 5 4 2 6 4

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2022년 12월 7일
a=[1 3 4
1 5 4
1 6 4
1 2 4
1 1 4
2 4 4
2 4 4
2 4 4
2 4 4
2 5 4
1 1 4
1 1 4
1 2 4
1 3 4
1 5 4
2 5 4
2 5 4
2 5 4
2 5 4
2 6 4];
b=reshape(a',3,5,[])
b =
b(:,:,1) = 1 1 1 1 1 3 5 6 2 1 4 4 4 4 4 b(:,:,2) = 2 2 2 2 2 4 4 4 4 5 4 4 4 4 4 b(:,:,3) = 1 1 1 1 1 1 1 2 3 5 4 4 4 4 4 b(:,:,4) = 2 2 2 2 2 5 5 5 5 6 4 4 4 4 4
c=transpose(squeeze(max(b,[],2)))
c = 4×3
1 6 4 2 5 4 1 5 4 2 6 4

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by