Reputation: 4565
I have column vectors A and B:
A'= [1 2 0 0 1 4]
B'= [1 2 3 4 5 6]
I would like to filter out the zeros in A and remove corresponding elements in B and have them as:
A' = [1 2 1 4]
B' = [1 2 5 6]
I know there is a quick MATLAB command to do this, but cant figure it out.
Upvotes: 3
Views: 3338
Reputation: 103
Another alternative is to remove the 0 element in A:
A0=A==0;
A(A0)=[];
B(A0)=[];
Howerver as @RodyOldenhuis said, A(A0)=[]
is slower than A=A(A0)
. So, when large loop is involved, or size of A is very large, A(A0)=[]
should be avoided to use.
Upvotes: 1
Reputation: 16195
You can condense the logical indexing solutions further by removing the intermediate variable and changing the syntax slightly.
B=B(~~A)
A=A(~~A)
The only slight possible pitfall with removing an intermediate variable (i.e. nz=~~A
) is that you have to remember to change B
before changing A
. This pitfall can be negated by converting the operation into a single command - the new values are not assigned to the variables until the right-hand-side of the expression has been evaluated.
[A,B] = deal(A(~~A),B(~~A))
Zen (if you're looking for the smallest amount of command characters), although I concur that efficiency might suffer (see comment).
Upvotes: 2
Reputation: 212969
You can just do it like this:
> A = [1 2 0 0 1 4]
A =
1 2 0 0 1 4
> B = [1 2 3 4 5 6]
B =
1 2 3 4 5 6
> V = find(A~=0) % get the indices for which A <> 0
V =
1 2 5 6
> A = A(V) % select elements from A
A =
1 2 1 4
> B = B(V) % select elements from B
B =
1 2 5 6
>
Upvotes: 1
Reputation: 38032
The quickest, easiest way is by using logical indexing:
A = [1 2 0 0 1 4].';
B = [1 2 3 4 5 6].';
nz = (A ~= 0); %# logical matrix for non-zeros in A
A = A(nz) %# non-zeros of A
B = B(nz) %# corresponding elements in B
Another way is the slightly slower
nz = find(A); %# vector of linear indices to non-zero elements
A = A(nz) %# non-zeros of A
B = B(nz) %# corresponding elements in B
Upvotes: 5