Home > OS >  Applying sparsity pattern to other matrix in matlab
Applying sparsity pattern to other matrix in matlab

Time:11-22

I'm trying to apply a sparsity pattern to another matrix. At the moment I'm just using assignment after using spalloc. The Matlab alerts that this is slow, but doesn't give a solution to make it faster. How do I apply the sparsity pattern of A to the matrix FWtrans? Meaning that the zero values of A have to be zero values in FWtrans. Only indices in A that have a value can have the value of FWtrans in X.

Wtrans = transpose(W);
As = sparse(A);
FWtrans = F * Wtrans;
[m,n] = size(FWtrans);
k = find(As);
X = spalloc(m,n, nnz(A));
% optimalize assignment too speed up
for i = k
    X(k) = FWtrans(k);
end 

CodePudding user response:

Instead of allocating the sparse array and then copying values to it, you can use sparse to allocate the array and assign the values all at once.

Wtrans = transpose(W);
As = sparse(A);
FWtrans = F * Wtrans;
[m,n] = size(FWtrans);

% unfortunately, sparse takes only row/column coordinates...
[r,c] = find(As);
% but it's more convenient to get the values using indices
v = FWtrans(find(As));

% let sparse allocate a m*n array and
% assign the values v to the proper locations
X = sparse(r, c, v, m, n);

It might be a bit quicker to use sub2ind after find in order to find the row/column coordinates instead of calling find twice, but I have my doubts.

See also: Accessing Sparse Matrices

  • Related