Problems specifying nzmax in sparse command from MATLAB -
Problems specifying nzmax in sparse command from MATLAB -
i create sparse matrix of size n × n. usual i, j row , column indices, s values. command
s=sparse(i,j,s,n,n);
works fine, uses lot of memory during creation of s. according documentation matlab uses nzmax=length(s) default. save memory, want specify nzmax s can compute in advance. testing purpose (i created s above command) calculate
nonzeros=nzmax(s);
and call
s=sparse(i,j,s,n,n,nonzeros);
note in illustration nonzeros much smaller length(s). also, nnz(s)=nzmax(s). error message
error using sparse: index exceeds matrix dimensions.
can explain behavior me, please? possible remedy/workaround?
let me add together code snippet example
i=randi(10,1000,1); j=randi(10,1000,1); s=rand(1000,1); ell=size((unique([i j],'rows')),1); s=sparse(i,j,s,10,10,ell); error using sparse: index exceeds matrix dimensions. s=sparse(i,j,s,10,10); nnz(s) ans = 100 ell ell = 100 nzmax(s) ans = 100
how using accumarray
, specifying you're working sparse matrices (the 6th argument):
n = 100; num = 10000; = randi(n,num,1); j = randi(n,num,1); s = ones(num, 1); = accumarray([i, j], s, [n,n], [], 0, true);
this uses next construction accumarray
:
a = accumarray(subs,val,sz,fun,fillval,issparse)
an alternative utilize spalloc
first. way should avoid default initialization.
a = spalloc(n, n, non_z); a(sub2ind(size(a),i,j)) = s;
yet alternative utilize unique
'rows'
sec input count number of unique index pairs.
uni_ind = numel(unique([i,j], 'rows')); = sparse(i, j, s, n, n, uni_ind);
matlab sparse-matrix
Comments
Post a Comment