Set null rows and columns except diagonal elements in matlab

Let's say I have been given some indices of type B = [10 23 32....];

Now let's say that I have matrix A. What I want to do is for each index from B, say i, I want to set the i-th column of the i-th column of A to 0, except for the diagonal element A (i, i) (it remains untouched).

I can do this by looping. But I want some of them to be based on some matrix multiplication, which is faster than just a loop.

Any ideas guys?

+6
source share
4 answers

You can temporarily store the diagonal elements somewhere else, index in with B to set the corresponding rows and columns to zeros and finally include them back in the diagonal elements -

 %// rows in A rows = size(A,1); %// Store the diagonal elements temporarily somewhere else tmp_diagA = A(1:rows+1:end); %// Set the ith rows and cols (obtained from B) to zero A(B,:)=0; A(:,B)=0; %// Plug back in the diagonal elements in place A(1:rows+1:end) = tmp_diagA; 

Functional calls should be expensive in MATLAB, and we have almost no function calls in this code, so I hope it will be fast enough.

+2
source

One of the options:

create linear indices of diagonal elements:

 [I, J]=size(A); idx=sub2ind([I,J], B, B); 

Set the horizontal and vertical to 0 and replace the diagonal elements:

 NewA=A; NewA(B, :)=zeros(numel(B),J); NewA(:, B)=zeros(I,numel(B)); NewA(idx)=A(idx); 
+1
source

For square A :

 b = zeros(size(A,1),1); b(B) = B; A = A.*bsxfun(@eq, b, b.') 

For general A :

 b1 = zeros(size(A,1),1); b1(B) = B; b2 = zeros(1,size(A,2)); b2(B) = B; A = A.*bsxfun(@eq, b1, b2); 
+1
source

Let's pretend that

 B=[10 23 32 12 15 18 20] M=true(6) M(B)=false %making the indexed elements false M=or(M,diag(true(size(M,1),1))) %keep the diagonal elements one % creating a matrix which has zero in ith row and ith column and diagonal has ones M1=and(bsxfun(@or,bsxfun(@and,repmat(min(M,[],2),1,size(M,2)),min(M,[],1)),diag(true(size(M,1),1))),M) %Now just multiply M1 with your matrix A, and you are done. newA=A.*M1 

You can combine the above two lines in one, but I prefer them to be disjoint for readability.

0
source

Source: https://habr.com/ru/post/975863/


All Articles