Reputation: 3488
Let's say we have the following sparse matrix defined by this 3 vectors:
[lines, columns, values] = find(A)
lines =
1
2
3
5
1
3
3
5
4
5
columns =
1
2
2
2
3
3
4
4
5
5
values =
3
4
7
3
1
5
9
6
2
5
What I am trying to achieve is to access the element at the position (2, 2)
I know you can do values(lines == 2)
(values(columns == 2)
) which will return all the values from second row (column).
My question is how can you do something like values(lines == 2 && columns == 2)
to get the value at A(2,2)
?
Upvotes: 0
Views: 6457
Reputation: 10686
In support of Robert's answer , here's a snapshot that proves that no conversion to full happens in accessing elements of a sparse matrix
I create a sparse matrix that would occupy 1e5^2 * 8bytes ~ 74.5 GB
in RAM if it were full.
Then I retrieve the subscripts to nonzero elements of S
and access the first element (without loss of generality).
On the right side of the pic, nowhere the memory jumps to > 16 GB. The only (hardly) noticeable bump happens when I create S
.
Upvotes: 1
Reputation: 14939
If you want to access elements in a sparse matrix, or any other matrix for that matter. This has no overhead whatsoever. If anyone can prove me wrong on this one, I would very much like to see a benchmark of it, because then I have missed something very important!
a = Q(2,2);
If you want to add elements to a sparse matrix, this is also very simple. I don't think there are any faster ways to do this either. Again, if anyone can prove me wrong, please share your benchmark results!
If you have:
lines = [ 1
2
3
5
1];
columns = [1
2
2
2
3];
values = [3
4
7
3
1];
Q = sparse(lines, columns, values)
(1, 1) -> 3
(2, 2) -> 4
(3, 2) -> 7
(5, 2) -> 3
(1, 3) -> 1
[linesF, columnsF, valuesF] = find(Q)
%% Now add the value 12 to position (3,1)
linesF = [linesF; 3];
columnsF = [columnsF; 1];
valuesF = [valuesF; 12];
Q = sparse(linesF, columnsF, valuesF)
(1, 1) -> 3
(3, 1) -> 12
(2, 2) -> 4
(3, 2) -> 7
(5, 2) -> 3
(1, 3) -> 1
This works because there is nothing saying the row and column vectors must be sorted in any way.
S = sprand(10000,10000,0.0005);
tic
for ii = 1:1000
var = S(r,c);
end
toc
Elapsed time is 0.010705 seconds.
[i,j,s] = find(S);
tic
for ii = 1:1000
var = s((i == r & j == c); % (r,c) is a random non-zero element in s
end
toc
Elapsed time is 0.296547 seconds.
Upvotes: 1