How best and most efficient way to build this matrix

Hi guys,
I am wondering what is the best and most efficient way to build this matrix using loops and functions? Rather than inputting the numbers manually?
A = [-2 1 0 0 0 0 0 0 0 0
6 -4 1 0 0 0 0 0 0 0
-4 6 -4 1 0 0 0 0 0 0
1 -4 6 -4 1 0 0 0 0 0
0 1 -4 6 -4 1 0 0 0 0
0 0 1 -4 6 -4 1 0 0 0
0 0 0 1 -4 6 -4 0 0 0
0 0 0 0 1 -4 6 -4 1 0
0 0 0 0 0 1 -4 6 -4 1
0 0 0 0 0 0 0 0 1 -2]
A = 10×10
-2 1 0 0 0 0 0 0 0 0 6 -4 1 0 0 0 0 0 0 0 -4 6 -4 1 0 0 0 0 0 0 1 -4 6 -4 1 0 0 0 0 0 0 1 -4 6 -4 1 0 0 0 0 0 0 1 -4 6 -4 1 0 0 0 0 0 0 1 -4 6 -4 0 0 0 0 0 0 0 1 -4 6 -4 1 0 0 0 0 0 0 1 -4 6 -4 1 0 0 0 0 0 0 0 0 1 -2
Many thanks

3 comentarios

In order to hope to answer about "the best and most efficient way" to build that matrix, we need you to rigoursly define "best" and also "most efficient" . And are you asking to know two different ways, one of which is "the best" and the other is "most efficient"? Because those are two different goals and trying to make it "best" might make it less "efficient" so if you need to satisfy both goals at the same time, we need to know the relative importance of those two goals in order to create a composite score.
Is "most efficient" in terms of time, or memory space, or code length?
If there is code that is twice as many lines of code, but is 1 nanosecond faster, then is that "most efficient" ?
If a piece of code is one nanosecond faster on your laptop but is 10 nanoseconds slower on your desktop, and 7 nanoseconds slower on your co-worker's desktop, then is it "most efficient" ?
Matt J
Matt J el 3 de Sept. de 2023
Has A(7,8) deliberately been made 0 instead of 1? If so, it is not clear what the pattern is supposed to be.
No, Matt, it should be 1. Sorry for the typo

Iniciar sesión para comentar.

 Respuesta aceptada

[C,R]=deal(zeros(1,10));
C(1:4)=[-4 6 -4 1];
R(1:2)=[-4,1];
A=toeplitz(C,R);
A(1)=-2;
A(end,:)=flip(A(1,:))
A = 10×10
-2 1 0 0 0 0 0 0 0 0 6 -4 1 0 0 0 0 0 0 0 -4 6 -4 1 0 0 0 0 0 0 1 -4 6 -4 1 0 0 0 0 0 0 1 -4 6 -4 1 0 0 0 0 0 0 1 -4 6 -4 1 0 0 0 0 0 0 1 -4 6 -4 1 0 0 0 0 0 0 1 -4 6 -4 1 0 0 0 0 0 0 1 -4 6 -4 1 0 0 0 0 0 0 0 0 1 -2

3 comentarios

Matt, could you explain what deal and toeplitz do?
Matt J
Matt J el 4 de Sept. de 2023
@Scott Banks for a full explanation, I suggest the documentation links provided by Walter.

Iniciar sesión para comentar.

Más respuestas (1)

Torsten
Torsten el 3 de Sept. de 2023
Movida: Torsten el 3 de Sept. de 2023
Experiment with "spdiags":
If first and last row appear different from your matrix, you can change them subsequently.

Categorías

Más información sobre Programming en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 3 de Sept. de 2023

Comentada:

el 4 de Sept. de 2023

Community Treasure Hunt

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

Start Hunting!

Translated by