How can I output specific point of data to a sparse matrix.
Show older comments
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.
Accepted Answer
More Answers (1)
Iain
on 20 May 2013
0 votes
The simple answer:
for k = 1:numel(i)
a(i(k),j(k)) = -1;
end
1-D or logical indexing is probably better suited.
4 Comments
James Tursa
on 21 May 2013
The for loop shown above has a potential data copy bottleneck that can severly decrease performance. Unless "a" is preallocated to have enough memory to contain all the values, the loop will repeatedly reallocate & copy data to make room for more values.
Iain
on 21 May 2013
Agreed, but he has preallocated ;)
James Tursa
on 21 May 2013
Edited: James Tursa
on 21 May 2013
No, he hasn't. That's the point. The command a = sparse(9,9) only creates an empty skeleton of a sparse matrix with no memory pre-allocated for any data. To get the data memory preallocated one would have to do something like a = sparse([],[],[],9,9,numel(J)). For a small matrix this data memory preallocation doesn't make much difference, but for a large matrix it can make a significant difference.
Another problem with the loop is sorting the data. Every time you add an element to the matrix in a loop MATLAB has to resort the internal data to make room for the new value. The loop forces MATLAB to do this one element at a time, which can cause repeated data copying of large chunks of memory again. Cedric's method above let's MATLAB do the necessary sorting in one fell swoop internally.
To illustrate:
>> n = 1000 ; % Square mat. size.
>> n_nz = 3*n ; % # non-zero elements.
>> A_full = zeros(n, n) ; % Full, for comparison.
>> A_spalloc = spalloc(n, n, n_nz) ;
>> A_sparse_prealloc = sparse([], [], [], n, n, n_nz) ;
>> A_sparse = sparse(n, n) ;
>> whos
Name Size Bytes Class Attributes
A_full 1000x1000 8000000 double
A_spalloc 1000x1000 56008 double sparse
A_sparse 1000x1000 8024 double sparse
A_sparse_prealloc 1000x1000 56008 double sparse
n 1x1 8 double
n_nz 1x1 8 double
The reference document if you want to understand how sparse matrices are stored, Iain, is the following: Gilbert et al., 1992
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!