MATLAB: Deleting rows in a matrix

matrixrows

Hi,
I have two matrices which are generated in a loop for n years:
A (m-rows x n-columns) B (k-rows)
Matrix B includes values which represent row numbers of matrix A that should be deleted. So, I want for every value in matrix B, the corresponding row in matrix A to be deleted.
For example,
A=[1 2; 2 2; 3 4], B= [2]
The result should be a matrix [1 2;3 4]. I.e. the middle row is deleted as B includes value 2.
For some reason I'm not able to find the correct coding for this. I tried several things, but inside the loop it doesn't work. This is what I tried, but this does't work:
for j= 1:n
B;
for i= 1:length(B)
indices = find(A(:,1)==B(i));
A(indices,:) = [];
end
end
Can anyone help me with this?

Best Answer

If you want to delete the second row because B has the value 2 you can use this vector to index into A as such:
A(B,:) = [];
That is how I interpret the question you pose, but the code seems to approach a different problem, outlined below.
If you want to delete the second row because the first element of A is 2, then you would find if each element of the first column of A is in the vector B and delete those locations:
locA = ismember(A(:,1),B); % Logical vector (true if A(i,1) is in B, false otherwise)
% use the logical vector to index into A and delete
A(locA,:) = [];