MATLAB: How to output specific point of data to a sparse matrix.

forifsparse matrix

Hi all,
I have a sparse matrix:
a = sparse(9,9)
I also have two sets of information:
i =
7
8
9
j =
1
2
6
So, I want to take i as a row reference and j as a column reference and output it to the sparse matrix. So, if I do:
a(i,j) = -1
Output Window:
a =
(7,1) -1
(8,1) -1
(9,1) -1
(7,2) -1
(8,2) -1
(9,2) -1
(7,6) -1
(8,6) -1
(9,6) -1
When I only want:
a =
(7,1) -1
(8,2) -1
(9,6) -1
or, I only to output to a when position of i is equal to position of j. I have tried certain things with "for" and "if" loops but haven't been able to come up with the right answer.
Can anyone please help me with this, thank you in advance.

Best Answer

It is much more efficient to build the matrix directly with "i", "j" as indices of non zeros elements and a vector of values (or a scalar), rather than building an empty matrix and indexing it later to set values. Example:
>> I = [4,2,8] ;
>> J = [1,7,3] ;
>> V = -1 ;
>> n = 9 ;
>> S = sparse(I, J, V, n, n)
S =
(4,1) -1
(8,3) -1
(2,7) -1
>> full(S)
ans =
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 -1 0 0
0 0 0 0 0 0 0 0 0
-1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 -1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
Now what you did wrong in your attempt is not related to sparse matrices, but to indexing. You could use e.g. SUB2IND to get a linear index based on "i" and "j", which would solve your problem.