MATLAB: How to remove additional rows from a matrix

additional rowsrestart while loop

Greetings! I have 2 matrices with sizes 103×2 and 101×2. 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

Best Answer

Note: you're taking a risk using length with a matrix. length is the size of the largest dimension so could be the number of rows, columns, pages, etc. depending on the matrix. It's much safer to use size with an explicit dimension, in your case size(a, 1) and size(b, 1).
I think you meant to use break instead of continue. continue means skip the rest of the body of the loop and proceed to the next iteration. Since it's the last instruction within the for loop, there's nothing left to skip, so it has absolutely no effect. break would break out of the while loop and proceed with the next iteration of the while loop.
Note that if all the values in the second column are different you don't need a loop at all:
a(~ismember(a(:, 2), b(:, 2)), :) = [];
And in any case, you don't need the inner loop:
while size(a, 1) > size(b, 1)
rowtodelete = find(a(1:size(b, 1), 2) ~= b(:, 2), 1);
if isempty(rowtodelete) %all element up to height of b match
a(size(b, 1)+1:end, :) = []; %delete remaining
else
a(rowtodelete, :) = []; %delete 1st non matching row
end
end
edit: fixed bug with 2nd algorithm.