How do I populate a 100 x 100 [A] matrix given rules seen below? Then use spy(A) to show non-zero entries?

8 views (last 30 days)
1, if i=j
Aij = 2, if i=j+1 or i=j-1
0, otherwise

Answers (2)

Steven Lord
Steven Lord on 12 Sep 2018
If you want this to be a sparse matrix, see the second example on the documentation page for the spdiags function. It's not exactly what you want, but you should be able to adapt it.

Stephen23
Stephen23 on 12 Sep 2018
Edited: Stephen23 on 12 Sep 2018
Method one: toeplitz (simple to resize):
>> V = zeros(1,10);
>> V(1) = 1;
>> V(2) = 2;
>> M = toeplitz(V,V)
M =
1 2 0 0 0 0 0 0 0 0
2 1 2 0 0 0 0 0 0 0
0 2 1 2 0 0 0 0 0 0
0 0 2 1 2 0 0 0 0 0
0 0 0 2 1 2 0 0 0 0
0 0 0 0 2 1 2 0 0 0
0 0 0 0 0 2 1 2 0 0
0 0 0 0 0 0 2 1 2 0
0 0 0 0 0 0 0 2 1 2
0 0 0 0 0 0 0 0 2 1
Method two: eye and indexing:
>> M = eye(10);
>> M(2:11:end) = 2;
>> M(11:11:end) = 2
M =
1 2 0 0 0 0 0 0 0 0
2 1 2 0 0 0 0 0 0 0
0 2 1 2 0 0 0 0 0 0
0 0 2 1 2 0 0 0 0 0
0 0 0 2 1 2 0 0 0 0
0 0 0 0 2 1 2 0 0 0
0 0 0 0 0 2 1 2 0 0
0 0 0 0 0 0 2 1 2 0
0 0 0 0 0 0 0 2 1 2
0 0 0 0 0 0 0 0 2 1
  5 Comments
John Steichen
John Steichen on 17 Sep 2018
@stephen Cobeldick can you explain what is happening in the lines of code where it changes the value? Its different than when you would go and change a single value in a matrix by specifying the row and column.
Stephen23
Stephen23 on 17 Sep 2018
"...can you explain what is happening in the lines of code where it changes the value?"
I used basic linear indexing. Linear indexing is one of the three kind of indexing that MATLAB supports. It works columnwise and uses a single index to access all elements of any array. YOu can learn about linear indexing by reading the MATLAB documentation:
Because each column contains 10 elements (in my examples), the step size for the linear index has to be 11, so as to move down one row in each subsequent column.

Sign in to comment.

Categories

Find more on Matrices and Arrays 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!