[英]Deleting elements from array in Matlab
Given, 鉴于,
a = [2 4 6 8 10 0 7 18 9 0 8 2 0 5];
b = [1 3 0 5 70 8 6 87 1 9 7 8 0 2];
I am trying to delete elements (in both 'a' & 'b') that corresponds to '0' or less than '0' in either 'a' or 'b' ie, I want 我正在尝试删除与“ a”或“ b”中的“ 0”或小于“ 0”相对应的元素(在“ a”和“ b”中),即我想要
% a = [2 4 8 10 7 18 9 8 2 5];
% b = [1 3 5 70 6 87 1 7 8 2];
I am trying like this - 我正在尝试这样-
n = length(b);
a1 = [];
b1 = [];
for k = 1:n
if a(n) <= 0 || b(n) <= 0
a1 = [a; a(a > 0)] % eliminates 0 from a
b1 = [b; b(b > 0)] % eliminates 0 from b
end
end
Any help will be very helpful. 任何帮助都会非常有帮助。
Use find
: 使用find
:
a = [2 4 6 8 10 0 7 18 9 0 8 2 0 5];
b = [1 3 0 5 70 8 6 87 1 9 7 8 0 2];
A = a( find( a > 0 & b > 0 ) );
B = b( find( a > 0 & b > 0 ) );
or even faster: 甚至更快:
C = a( a > 0 & b > 0 );
D = b( a > 0 & b > 0 );
returns: 收益:
C =
2 4 8 10 7 18 9 8 2 5
D =
1 3 5 70 6 87 1 7 8 2
If you can be sure, that there are no values below zero you could also use: 如果可以确定没有零以下的值 ,也可以使用:
E = a( logical(a) & logical(b) );
F = b( logical(a) & logical(b) );
which is a little faster, but containing also negative values. 速度稍快,但也包含负值。
The efficient and compact way to do this is to first create the relevant index, that prevents double calculation: 一种有效而紧凑的方法是首先创建相关索引,以防止重复计算:
idx = a>0 & b>0
a = a(idx);
b = b(idx);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.