How to remove additional rows from a matrix?
이전 댓글 표시
Greetings! I have 2 matrices with sizes 103x2 and 101x2. The 2 rows that I want to remove are not the last ones in the first matrix. Those matrices have been created so that the second column has the same elements for each matrix. I have ran a code which I include and checks each line of the matrices to determine whether the elements in the second column are equal or not. If they are not equal then the row from the first matrix should be deleted and then the loop should start over. After running the code I get an error message which states that index exceeds matrix dimensions. I even tried to make them equal by adding zeros and the run again the code but it didn't work. I can't figure out what am I missing. Can anyone help? Thanks in advance.
i=0;
while i<abs(length(a)-length(b))
for j=1:max(length(a),length(b))
if (a(j,2)~=b(j,2))
a(j,:)=[];
i=i+1;
continue;
end
end
end
채택된 답변
추가 답변 (1개)
Azzi Abdelmalek
2016년 8월 17일
편집: Azzi Abdelmalek
2016년 8월 17일
b(j,2) is not defined for j=max(length(a),length(b))
What are you expecting as result for this small example:
a=[4 1;5 2;6 3;7 4;9 10;1 5;8 7]
b=[3 1;5 7;8 3;4 87 ;2 10]
댓글 수: 4
Paschalis Garouniatis
2016년 8월 17일
Azzi Abdelmalek
2016년 8월 17일
a=[4 1;5 2;6 3;1 8;10 7;88 4]
b=[3 1;5 3;2 8;9 7]
n=size(a,1)
m=size(b,1)
p=n-m
ii=0
jj=0
for k=1:m
ii=ii+1
if a(k,2)~=b(k,2) & jj<p
a(ii,:)=[]
ii=ii-1
jj=jj+1
elseif jj==p
break
end
end
a(m+1:end,:)=[]
Guillaume
2016년 8월 18일
Note that with either example
a(~ismember(a(:, 2), b(:, 2)), :) = []
as per my answer is enough to do the job. It will do the job as long as the values in the 2nd column of B are unique.
Paschalis Garouniatis
2016년 8월 18일
편집: Paschalis Garouniatis
2016년 8월 18일
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!