How do I fill a matrix with values using the tril, diag function without it overwritting the previous command?

4 次查看(过去 30 天)
Hello. I am trying to do the following in a matrix. Please see attached. The code that I came up with keeps overwriting the previous code for the A matrix.
%Makes a 121 by 121 matrix of zeros
A=zeros(121);
%This makes a 121 by 121 matrix of ones
B = ones(121);
%This is element by element multiplication
matrix_I=-I.*B;
%This is the row vector for to get the ones in the 'A' matrix
V=ones(1,120);
%This makes the diagonal of ones in the 'A' matrix
A = diag(V,1);
A= tril(matrix_I);
A(120, 121) = -1;
%This is for all the -1 being multiplied by M
%for the given equation in book P3.4a but I solved it and set it equal to 0
A(:,121)=-1;
Please I need some help. Thank you.
  2 个评论
JoshT_student
JoshT_student 2018-8-1
No, I want the lower diagonal of the matrix to be some number. Like for example -0.33. But I still need the diagonal of 1s after the -0.33 like in the picture I attached; And still have the zeros after it and then have -1 in the last column of each row.

请先登录,再进行评论。

采纳的回答

Rik
Rik 2018-8-2
编辑:Rik 2018-8-3
You're close, see if the code below works for you.
I fixed some typos in the previous code. Now it runs and should give you the output you want.
num_el=121;I=1/3;
D=ones(num_el-1);%it's easier to skip the first column and last row first
A=tril(-I.*D);
A(1:(size(A,2)+1):end)=1;
A=[ones(num_el-1,1)*-I A;ones(1,num_el-1)*-I -1];
A(:,end)=-1;
  2 个评论
Rik
Rik 2018-8-5
Did this suggestion solve your problem? If so, please consider marking it as accepted answer. It will make it easier for other people with the same question to find an answer. If this didn't solve your question, please comment with what problems you are still having.
JoshT_student
JoshT_student 2018-8-5
Thank you Mr. Wisselink. It works great. I also found on research gate that this is another to do it too:
n = 121;
a = -0.333;
A = tril(ones(n,n)*a) + diag(ones(n-1,1),1);
A(:,end) = -1;
A(120,121)=1;
Thank you again.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by