简体   繁体   English

从非零索引处的向量中减去行和列

[英]Subtracting rows and columns from a vector at non-zero indices MATLAB

Suppose I have the following matrix in MATLAB: 假设我在MATLAB中具有以下矩阵:

A =[0    0    4    0; 
    0    5    0    3; 
    1    2    0    0];

given the following vectors: 给定以下向量:

b1 = [1 2 3];
b2 = [2 3 4 5];

the output should look like this: 输出应如下所示:

C1 =[0    0    3    0; 
     0    3    0    1; 
    -2   -1    0    0];

C2 =[0    0    0    0; 
     0    2    0   -2; 
    -2   -1    0    0];

C1 and C2 are column-wise and row-wise subtraction of the original matrix A from vectors happening at non-zero elements . C1和C2是原始矩阵A在非零元素处发生的矢量的按列和按行减法。 Note A in reality is sparse matrix . 注意,实际上A是稀疏矩阵 Obviously answers without using loop is appreciated! 显然不使用循环的答案表示赞赏! Thank you 谢谢

This one might be a little more memory efficient: 这可能会提高内存效率:

A =[0    0    4    0; 
    0    5    0    3; 
    1    2    0    0];

b1 = [1 2 3].';   % transpose so it's a column vector
b2 = [2 3 4 5].';

[Arows Acols Avals] = find(A);
C1 = sparse([Arows;Arows], [Acols;Acols], [Avals;-b1(Arows)]);
C2 = sparse([Arows;Arows], [Acols;Acols], [Avals;-b2(Acols)]);

Results: 结果:

>> full(C1)
ans =

   0   0   3   0
   0   3   0   1
  -2  -1   0   0

>> full(C2)
ans =

   0   0   0   0
   0   2   0  -2
  -1  -1   0   0

This takes advantage of the fact that sparse adds the values given for duplicate subscripts. 这利用了sparse将重复下标给出的值相加这一事实。 A can be sparse or full. A可以是稀疏的或完整的。

No need to use a loop. 无需使用循环。 First perform the subtractions and then replace the elements that should remain 0 . 首先执行减法,然后替换应保持为0的元素。

C1 = A - repmat(b1.',1,size(A,2));
C2 = A - repmat(b2,size(A,1),1);
C1(A==0)=0;
C2(A==0)=0;

C1 =

     0     0     3     0
     0     3     0     1
    -2    -1     0     0

C2 =

     0     0     0     0
     0     2     0    -2
    -1    -1     0     0

Test on Sparse Matrix 测试稀疏矩阵

You can also confirm that this will work on Sparse Matirces 您还可以确认这将适用于稀疏母ir

A = sparse(10,10);
A(5:6,5:6)=rand(2);
b1 = rand(10,1);
b2 = rand(1,10);

B1 = A - repmat(b1,1,size(A,2));
B2 = A - repmat(b2,size(A,1),1);

B1(A==0)=0;
B2(A==0)=0;
C1 = A ~= 0; // save none zero elements of A
b1 = b1.';   // transpose b1
b1 = [b1, b1, b1, b1];  // create matrix of same size as A
C1 = C1.*b1;            
C1 = A-C1;

C1: C1:

 0     0     3     0
 0     3     0     1
-2    -1     0     0

Next is C2 接下来是C2

 C2 = A ~= 0;
 k = [b2; b2; b2];
 C2 = C2.*k;
 C2 = A-C2;

C2: C2:

 0     0     0     0
 0     2     0    -2
-1    -1     0     0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM