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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With