please see the attached image i need to create a tridiagonal nxn matrix using the diag function. i know how to make it this way but thats not what is required.
>> A=[2 -1 0 0 0;-1 2 -1 0 0;0 -1 2 -1 0;0 0 -1 2 -1; 0 0 0 -1 2]
A =
2 -1 0 0 0
-1 2 -1 0 0
0 -1 2 -1 0
0 0 -1 2 -1
0 0 0 -1 2

1 Kommentar

James Tursa
James Tursa am 24 Mär. 2015
"... not what is required."
Is this homework? Have you reviewed the doc on diag to see how to get values into the off-diagonals?

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Konstantinos Sofos
Konstantinos Sofos am 24 Mär. 2015

0 Stimmen

Hi,
As James wrote you:Have you reviewed the doc on diag to see how to get values into the off-diagonals?
Mathworks offers an excellent documentation for such topics with plenty of examples.
You could use this
function Out = mydiag(n)
%n size of matrix Out
Out= diag(-1*ones(1,n-1),-1) + diag(2*ones(1,n)) + diag(-1*ones(1,n-1),1);
end
>> mydiag(5)
ans =
2 -1 0 0 0
-1 2 -1 0 0
0 -1 2 -1 0
0 0 -1 2 -1
0 0 0 -1 2

Weitere Antworten (0)

Kategorien

Mehr zu Testing Frameworks finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by