Populating a matrix with variables

Hello,
I am currently working on some finite volume method problems and as such I need to populate a matrix diagonal, I have used the 'diag' function successfully for populating the matrix with numbers but I would like to insert variables in the matrix diagonal. Would someone be able to advise me on the best way to do this. I am looking for something like the matrix included below, I know I could easily type in a matrix of that size but something of the 100*100 size just isn't practical.
Thanks for your help.
a_p1 a_e1 0 0 0
a_w2 a_p2 a_e2 0 0
0 a_w3 a_p3 a_e3 0
0 0 a_w4 a_p4 a_e4
0 0 0 a_w5 a_p5
P.S. I am fairly new to Matlab and I am using this finite volume method problem as a way to learning the software.

回答 (1 件)

Massimo Zanetti
Massimo Zanetti 2016 年 9 月 29 日

3 投票

Best way to populate diagonal matrix is to use spdiags (see help page).
For example, to obtain
A=[1,2,0,0,0,0;
0,2,3,0,0,0;
0,0,3,4,0,0;
0,0,0,4,5,0;
0,0,0,0,5,6];
Do this:
%define a matrix where columns are the diagonals
D = [1,2;
2,3;
3,4;
4,5;
5,6];
%put the columns in diagonal positions 0 (main diag) and 1 (upper diag)
%and specify matrix size 5x6
A = full(spdiags(D,[0,1],5,6));

4 件のコメント

Steven Taggart
Steven Taggart 2016 年 9 月 29 日
Hi Massimo thanks for your answer! Would that work with variables rather than numbers?
Ideally id like to define a diagonal like a_1...a_n and be able to define 'n'.
Massimo Zanetti
Massimo Zanetti 2016 年 9 月 29 日
I don't get you..
Steven Taggart
Steven Taggart 2016 年 9 月 29 日
If I was looking to make a 80*80 matrix is there a way I could say a_1...a_80 without typing it all out.
Thanks
Massimo Zanetti
Massimo Zanetti 2016 年 9 月 29 日
what are the real numbers that have to populate the matrix? a_1=? a_2=? .....

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeOperating on Diagonal Matrices についてさらに検索

質問済み:

2016 年 9 月 29 日

コメント済み:

2016 年 9 月 29 日

Community Treasure Hunt

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

Start Hunting!

Translated by