从矩阵/向量中提取两个数之间的元素

时间:2016-07-11 12:59:28

标签: matlab matrix extract

例如,我有一个4x4矩阵

In [18]:
df = pd.DataFrame({'a':np.random.randn(5), 'b':np.arange(5)})
df

Out[18]:
          a  b
0 -0.118930  0
1 -0.129362  1
2  0.822227  2
3  1.781672  3
4 -0.127322  4

In [19]:
df.loc[df['b'].isin([2,4])]

Out[19]:
          a  b
2  0.822227  2
4 -0.127322  4

对于每一行,我想提取1到3之间的元素(假设矩阵总是有一些介于1和3之间的元素,1总是在3之前)。例如,返回像[{2},{4},{2,4},{2}]这样的单元格,甚至更好地使用矩阵

   A = [1,    2,    3,    4;
        2,    1,    4,    3;
        1,    2,    4,    3;
        4,    1,    2,    3;];

现在我为每一行做一个循环,找到索引1和3,然后将它们之间的索引设置为零,即

B=  [0,    1,    0,    0;
     0,    0,    0,    1;
     0,    1,    0,    1;
     0,    1,    0,    0;];

生成此矩阵B或仅生成单元格的更简单方法?任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:4)

好吧,这可能不是一个更简单的解决方案,但它确实删除了循环,所以它应该在计算上更快:

这个想法不是试图找到1到3之间的数字而是将它们设置为1,我将找到1和3之外的数字并将它们设置为0:

B=zeros(4,4);
B(A == 1) = 1;
B(A == 3) = 1;
C = cumsum(B')';
B(C>=2) =1;
B(C< 1) =1;

%finally you want to invert this:
B = (B-1)*-1;

>> B =

 0     1     0     0
 0     0     1     0
 0     1     1     0
 0     0     1     0

==========此部分适用于您的第二次编辑后==========

 D = A.*B % this seems to be the cell indexes you are after?

 D =

 0     2     0     0
 0     0     4     0
 0     2     4     0
 0     0     2     0

E = zeros(4,4);
for t = 1:size(A,1)
   E(t,D(t,D(t,:)>0)) = 1;  %This re-applies the index numbers and create a new index matrix through a loop........
   %or you can use E(t,D(t,~~D(t,:))) = 1 to same effect, Thanks to @Dev-iL
end


>> E =

 0     1     0     0
 0     0     0     1
 0     1     0     1
 0     1     0     0

这将为A提供1到3之间元素的索引,然后您可以使用逻辑索引来查找所需的单元格数。

答案 1 :(得分:2)

我的解决方案与已经建议的解决方案没有什么不同,但它有一个bsxfun,所以我说 - 为什么不呢? :)

function B = q38307616

A = [1,    2,    3,    4;
     2,    1,    4,    3;
     1,    2,    4,    3;
     4,    1,    2,    3;];

At = A.';

tmp = arrayfun(@colon,find(At==1)+1,find(At==3)-1,'UniformOutput',false);
% [tmp{:}] gives us the indices of the elements we should be considering

B = 0*A; %preallocation
for ind1 = 1: numel(tmp)
  B(ind1,:) = sum(bsxfun(@eq,At(tmp{ind1}).',1:4),1); %1:4 are the allowable values
end

&#34;奖励&#34;:获取每行1到3之间元素的逻辑映射的另一种方法,与GameOfThrows' B相同,是:

tmp2 = reshape(full(sparse(~~[tmp{:}],[tmp{:}],~~[tmp{:}],1,numel(A)).'),size(A));
相关问题