根据另一个向量的条件从向量中选择元素

时间:2019-06-05 13:33:51

标签: arrays matlab vector subset matrix-indexing

我想知道如何选择与我的预定义数字相对应(即相同位置)的数字。

例如,我有以下向量:

ps-u[username]

我需要从ps -u [username] -o stat,cmd --sort=-pid | awk '{print $2$3$4}' 中选择与a = [ 1 0.1 2 3 0.1 0.5 4 0.1]; b = [100 200 300 400 500 600 700 800] 中的整数位置(1、2、3和4)相对应的元素,因此输出必须为:

b

这怎么办?

4 个答案:

答案 0 :(得分:2)

基于a创建逻辑索引,并将其应用于ab以获得所需的结果:

ind = ~mod(a,1); % true for integer numbers
output = [a(ind); b(ind)].'; % build result

答案 1 :(得分:1)

尽管意图不明确,但创建矩阵索引是解决方案

我的解决方法是

checkint = @(x) ~isinf(x) & floor(x) == x % It's very fast in a big array
[a(checkint(a))' b(checkint(a))']

此处的关键是创建到ab的索引,它们是a中整数值的逻辑向量。此功能checkint很好地检查了整数。

其他检查整数的方法可能是

checkint = @(x)double(uint64(x))==x % Slower but it works fine

checkint = @(x) mod(x,1) == 0 % Slowest, but it's robust and better for understanding what's going on

checkint = @(x) ~mod(x,1) % Slowest, treat 0 as false

已经在许多其他主题中进行了讨论。

答案 2 :(得分:1)

round(x) == x ----> x is a whole number
round(x) ~= x ----> x is not a whole number
round(2.4) = 2 ------> round(2.4) ~= 2.4 --> 2.4 is not a whole number
round(2) = 2 --------> round(2)   == 2 ----> 2 is a whole number

遵循相同的逻辑

a = [  1 0.1   2   3 0.1 0.5   4 0.1];
b = [100 200 300 400 500 600 700 800 700];
iswhole = (round(a) == a);
output = [a(iswhole); b(iswhole)]

结果:

output =

     1     2     3     4
   100   300   400   700

答案 3 :(得分:1)

我们可以基于使用fix()函数生成逻辑索引

enter code here
相关问题