Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the particular row and column zeros except the diagonal elements in matlab

Tags:

matlab

Lets say I am given some indices like B = [10 23 32....];

Now lets say I have a matrix A. What I want to do is for each index from B lets say i, I want to set the ith row and ith column of A to 0 except the diagonal element A(i,i)(it remains untouched).

I can do this by looping. But I want some that is based upon some matrix multiplication which is quicker than just looping.

Any ideas guys?

like image 364
user12331 Avatar asked Sep 25 '14 23:09

user12331


People also ask

How do you select a diagonal element in Matlab?

D = diag( v ) returns a square diagonal matrix with the elements of vector v on the main diagonal. D = diag( v , k ) places the elements of vector v on the k th diagonal. k=0 represents the main diagonal, k>0 is above the main diagonal, and k<0 is below the main diagonal.

How do you set a matrix to zero in MATLAB?

Set Matrix Zeroes Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0 's, and return the matrix. You must do it in place. A straightforward solution using O (mn) space is probably a bad idea. A simple improvement uses O (m + n) space, but still not the best solution.

What is the difference between zero row and zero column set?

For the above example, set ‘zero_rows’ consists of two elements, 1 and 2 because there is a zero in row 1 and row 2. Similarly, set ‘zero_columns’ consists of two elements, 1 and 3 because there is a zero in column 1 and column 3.

How to create an empty array with zeros in MATLAB?

The Matlab inbuilt method zeros () creates array containing all element as zero or empty value. This function allows user an empty array having a bunch of zeros in it. The Matlab programming language does not contain any dimension statement. In Matlab, storage allocation for matrices happens automatically.

How do you find the zero value of a 2D matrix?

O (m + n). One naive solution which may come to the mind is to do a scan of the 2D matrix and upon seeing a zero, make that whole column and row zero. But that is not correct; even if there is only 1 zero in the matrix, this will make the whole matrix zero.


1 Answers

You can store the diagonal elements temporarily somewhere else, index into A with B to set the corresponding rows and columns to zeros and finally plug 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;

Function calls are supposed to be expensive in MATLAB and we have almost have no function calls in this code, so I am hoping it to be fast enough.

like image 176
Divakar Avatar answered Oct 25 '22 17:10

Divakar