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!