Delete number in two matrices with same indices/position
14 views (last 30 days)
Hi... How can i delete numbers in two different matrices with same position? Example: A = [1 2 4 5;2 4 5 6; 3 7 8 2]; B = [3 4 5 6;0 10 4 1;4 12 34 56];
then if i want remove value 2 in matrix A, in the same time i need to delete the value at same position in matrix B.
the answer will get are: A = [1 4 5;4 5 6; 3 7 8]; B = [3 5 6;10 4 1;4 12 34];
Walter Roberson on 3 Feb 2012
At = A .';
Bt = B .';
pos = find(At(:) == 2);
At(pos) = ;
Bt(pos) = ;
A = reshape(At, size(A,2), ) .';
B = reshape(Bt, size(B,2), ) .';
And do not be surprised if the reshape step fails, as in the general case there is no reason to believe that their will be exactly the same number of matches per row.
Note: when you delete an element in MATLAB, MATLAB "pulls up" elements from below in the same column . You want to "pull over" from the same row. That is why the two transposes are needed.
Kevin Moerman on 3 Feb 2012
If A and B are the save size then instead of the "find" function (which produces linear or subscript indices) use logic indexing for speed e.g.:
L=A==2; A(L)=; B(L)=;
Reshape is not required (and is slow for large arrays). The approach above and that of Mr. Roberson only work if the empty entries of  lead to the removal of say always n colums or n rows. In other cases you'll get an error. You could use sparse arrays and set the entries to zero instead or use NaN.
Good luck, Kevin