Clear Filters
Clear Filters

I'm trying to create a n by n sparse matrix with 3*xi-xi^2 on the main diagonal of K, and with with 6*xi on the sup-diagonal of K , where i starts from 1 to n. And everywhere else 0. Can anyone please tell me how to get that ?

1 view (last 30 days)
Before I created a matrix that the main diagonal of K are alternatively 2 and -2’s, the sub- and sup-diagonal of K alternatively 1 and -1’s, and everywhere else 0.
n = 5;
k = mod(1:n,2)*2 - 1;
A = diag(k*2) + diag(k(1:n-1),-1) + diag(k(1:n-1),1)
But since now the number on the diagonal has to be different. I can't use this approach.

Answers (1)

Steven Lord
Steven Lord on 17 Apr 2017
Consider building the index and data vectors and calling sparse once using those vectors. See the "Accumulate Values into Sparse Matrix" example on the documentation page for an example that builds a sparse matrix using those vectors. You'll have two "pieces" of each vector: one piece for the main diagonal and one piece for the super-diagonal.
Alternately, use the spdiags function.


Find more on Sparse 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!