How can I output specific point of data to a sparse 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.
채택된 답변
추가 답변 (1개)
Iain
2013년 5월 20일
0 개 추천
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
James Tursa
2013년 5월 21일
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
2013년 5월 21일
Agreed, but he has preallocated ;)
James Tursa
2013년 5월 21일
편집: James Tursa
2013년 5월 21일
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
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!