omit rows of matrix based on a condition

1 回表示 (過去 30 日間)
Pooneh Shah Malekpoor
Pooneh Shah Malekpoor 2022 年 10 月 15 日
コメント済み: David Hill 2022 年 10 月 15 日
Hello
My matrix B is :
[0.25 0 0;
0.5 -4.91 -4.9;
0.75 -4.94 -4.96;
1 -4.985 -5;
1.25 -5 -5;
1.5 -5 -5;
1.75 -5 -5]
How to write a code to omit all the rows (except from first row and fifth row 1.25,-5,-5) where column 2 and three are equal. I mean keep the first and fifth row where column 2 and 3 are equal but omit other rows with the same situation.

採用された回答

David Hill
David Hill 2022 年 10 月 15 日
編集済み: David Hill 2022 年 10 月 15 日
Seems like there are more than just two rows.
B=[0.25 0 0;
0.5 -4.91 -4.9;
0.75 -4.94 -4.96;
1 -4.985 -5;
1.25 -5 -5;
1.5 -5 -5;
1.75 -5 -5];
[~,idx]=unique(B(:,2),'stable');
C=B(idx,:);
C(C(:,2)~=C(:,3),:)=[];
C
C = 2×3
0.2500 0 0 1.2500 -5.0000 -5.0000
  2 件のコメント
Pooneh Shah Malekpoor
Pooneh Shah Malekpoor 2022 年 10 月 15 日
Thanks, Then how to get [0.25 0 0;
0.5 -4.91 -4.9;
0.75 -4.94 -4.96;
1 -4.985 -5;
1.25 -5 -5]???
David Hill
David Hill 2022 年 10 月 15 日
B=[0.25 0 0;
0.5 -4.91 -4.9;
0.75 -4.94 -4.96;
1 -4.985 -5;
1.25 -5 -5;
1.5 -5 -5;
1.75 -5 -5];
[~,idx]=unique(B(:,2),'stable');
C=B(idx,:)
C = 5×3
0.2500 0 0 0.5000 -4.9100 -4.9000 0.7500 -4.9400 -4.9600 1.0000 -4.9850 -5.0000 1.2500 -5.0000 -5.0000

サインインしてコメントする。

その他の回答 (2 件)

Torsten
Torsten 2022 年 10 月 15 日
B = [0.25 0 0;
0.5 -4.91 -4.9;
0.75 -4.94 -4.96;
1 -4.985 -5;
1.25 -5 -5;
1.5 -5 -5;
1.75 -5 -5];
B = B(union(find(B(:,2)~=B(:,3)),[1 5]),:)
B = 5×3
0.2500 0 0 0.5000 -4.9100 -4.9000 0.7500 -4.9400 -4.9600 1.0000 -4.9850 -5.0000 1.2500 -5.0000 -5.0000

Ghazwan
Ghazwan 2022 年 10 月 15 日
%If you already know that you need to omit the first and last row only
A=A(2:end-1,:);
%If you do not know which rows have the condition
for ii=1:length(A(:,1))
if A(ii,2)==A(ii,3) %Your condition
A(ii,:)=[]; %omitting the row that meets the condition
end
end
  1 件のコメント
Pooneh Shah Malekpoor
Pooneh Shah Malekpoor 2022 年 10 月 15 日
Thanks but it keeps the last row while I want it to keep the first row with equal arrays in column 2 and 3 (I mean I want a for loop which keep the fifth row). How?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by