# How to speed up sparse matrix index operation in Matlab?

I need to create spare matrices with variable elements. Unfortunately, sparse matrix index operations are very slow.

Is there any way to speed up the process? Maybe there are some tricks that I don't know of?

n=100;
n1=prod([6,n,n]);
n2=prod([3,n,3,n]);
X=sparse(n1,n2);
for i=1:n1
X(i,i)=1;
end
for i=n1-prod([n,n,3])+1:n1-prod([n,n,2])
for j=n1+1:n1+prod([n,n])
X(i,j)=1;
end
end
for i=n1-prod([n,n,2])+1:n1-prod([n,n])
for j=n1+1+prod([n,n]):n1+prod([n,n,2])
X(i,j)=1;
end
end
for i=n1-prod([n,n,1])+1:n1
for j=n1+1+prod([n,n,2]):n1+prod([n,n,3])
X(i,j)=1;
end
end
%disp(X);
sigm = svds(X, 1);


The above code says "This sparse index expression may be slow" at line 6.How to improve it?Any help would be highly appreciated.

This post, Creating Sparse Finite-Element Matrices in MATLAB, explains why creating sparse matrix entries in MATLAB using indexes is a very slow operation and describes a much faster approach using the sparse() function.