## Creating sparse matrices from sparse vectors

### Creating sparse matrices from sparse vectors

Hi,

I have found some problems in building a sparse matrix from a
sparse vector that contains the matrix entries. This is what I am
doing:

Quote:>> whos

Name        Size       Elements     Bytes    Density   Complex

ans       1 by 1             1         8       Full      No
i    4585 by 1          4585     36680       Full      No
j    4585 by 1          4585     36680       Full      No
x     515 by 668        4585     57692     0.0133      No
z    4585 by 1          3764     45172     0.8209      No

Quote:>> y = sparse(i,j,z,size(x,1),size(x,2));

WARNING: Possible memory leak.
Freeing element at address 0x40328b88 with allocation count    64777
Freeing element at address 0x402dcbb0 with allocation count    64776

And I receive this awful message!!!

Can anybody help me to figure where the problem is?

Thank you
Oscar Yanez

Given a row vector, n:

n = [ 1 3 0 4 6 0 2];

is there a "vectorized" (i.e. clever) way to get a matrix A, such that

A = [ 1 0 0 0 0 0 0;
0 0 0 0 0 0 1;
0 1 0 0 0 0 0;
0 0 0 1 0 0 0;
0 0 0 0 0 0 0;
0 0 0 0 1 0 0 ];

in other words, A is sparse, with only nonzero elements:

A(n(1),1) = 1;
A(n(2),2) = 1;
A(n(3),3) = 1;
etc...

For zero elements in n, the corresponding column would be all zeros...

I tried using "sparse", which works fine if all elements of n are valid
subscripts (nonzero), but it fails if some elements of n are 0.

S = sparse(n,1:length(n),ones(size(n)));  % works, but only if n has all
nonzero elements!

Any help is appreciated...thanks.

Fran Maurais