逻辑索引而不是查找

时间:2013-02-24 11:27:19

标签: matlab

我想改进一段代码

LaserS_P=rand(20,3); % duumy data
LaserS_P(1:4:end,1)=0;
index_= find( LaserS_P(:,1)); % finds o element in first row of 20*3 matrix.
LaserS_P_new=LaserS_P(index_,:); % remove all rows (index_) from matrix

如何在这种情况下使用逻辑索引。

1 个答案:

答案 0 :(得分:5)

要删除所有零值行(这不是您的示例所做的),您可以使用逻辑索引,如下所示:

LaserS_P=rand(20,3); % dummy data
LaserS_P(1:4:end,1)=0;
index_= ( LaserS_P(:,1) == 0); %# finds 0 element in first col of 20*3 matrix.
%# index_ is a logical vector with ones wherever LaserS_P's first col is 0
LaserS_P_new=LaserS_P(~index_,:); %# remove all rows (index_) from matrix

%# alternatively
LaserS_P_new(index_,:) = []; %# remove all rows (index_) from matrix