在matlab中过滤矩阵

dr_*_*_rk 3 matlab

我有列向量A和B:

A'= [1 2 0 0 1 4]
B'= [1 2 3 4 5 6]
Run Code Online (Sandbox Code Playgroud)

我想过滤掉A中的零并删除B中的相应元素并将它们作为:

A' = [1 2 1 4] 
B' = [1 2 5 6]
Run Code Online (Sandbox Code Playgroud)

我知道有一个快速的MATLAB命令来做到这一点,但无法弄清楚.

Rod*_*uis 5

最快捷,最简单的方法是使用逻辑索引:

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
Run Code Online (Sandbox Code Playgroud)

另一种方式是稍慢

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
Run Code Online (Sandbox Code Playgroud)