Filter löschen
Filter löschen

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

3 Ansichten (letzte 30 Tage)
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 Kommentare
JoshT_student
JoshT_student am 1 Aug. 2018
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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Rik
Rik am 2 Aug. 2018
Bearbeitet: Rik am 3 Aug. 2018
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 Kommentare
Rik
Rik am 5 Aug. 2018
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 am 5 Aug. 2018
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Operating on Diagonal Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by