How to make a for loop with matrices using n?

3 views (last 30 days)
I am trying to make a matrix that is easy for me to change it's dimension while it's overall appearance stays the same. However, matlab does not seem to like the k=1:n part of my code below. Any tips on how to fix it without putting 10 instead of n? I do not get any error no matter how long I let the program run; the matrix simply stays a zero matrix.
n=10;
A=zeros(n,n);
n=10;
for k=1:n
A(k,k)=2;
end
for k=1:(n-1)
A(k,k+1)=-1;
end
for k=1:(n-1)
A(k+1,k)=-1;
end
A(1,1)=1;

Accepted Answer

Stephen23
Stephen23 on 22 Mar 2019
Edited: Stephen23 on 22 Mar 2019
>> n = 10;
>> A = toeplitz([2,-1,zeros(1,n-2)])
A =
2 -1 0 0 0 0 0 0 0 0
-1 2 -1 0 0 0 0 0 0 0
0 -1 2 -1 0 0 0 0 0 0
0 0 -1 2 -1 0 0 0 0 0
0 0 0 -1 2 -1 0 0 0 0
0 0 0 0 -1 2 -1 0 0 0
0 0 0 0 0 -1 2 -1 0 0
0 0 0 0 0 0 -1 2 -1 0
0 0 0 0 0 0 0 -1 2 -1
0 0 0 0 0 0 0 0 -1 2

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!