Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Matrix in matlab

Tags:

matlab

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.

like image 534
dr_rk Avatar asked Apr 14 '26 09:04

dr_rk


1 Answers

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
like image 78
Rody Oldenhuis Avatar answered Apr 16 '26 21:04

Rody Oldenhuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!