MATLAB write a function that generates n x n matrix WITHOUT built in functions.

24 visualizzazioni (ultimi 30 giorni)
This problem requires me to use nested for loops to create matrix S of any given size. I took this to mean that the input would be an integer and output would be a matrix that is S=S^(-1) (invesre matrix) and that S*S=I (identity matrix). I'm a MATLAB beginner but so far I have this.
n=input("enter value of n: ");
S=zeros(n,n);
for i = 1:n
for j = 1:n
S(i,j)=i*j; % This is the part of the code I don't know how to fix.
end
end
S %prints matrix S
B = A' + A;
B(1:n+1:end)=diag(A); %This part is supposed to take any square matrix and turn it symmetrical, it wont be nessesary if I can accomplish this is the first part of code.
C=inv(B);
C %should equal Identity matrix to check if my code worked correctly.
This code spits out a matrix but i cannot seem to find a way to (1) get it to give me a symmetrical matrix or (2) generate a matrix that I can then transform into a symmetrical matrix. If it helps at all the end goal is to have a matrix I can use as a DST (discrete sine transform) Any help would be appreciated thx.

Risposte (1)

Walter Roberson
Walter Roberson il 14 Apr 2021
Your S is symmetric.
However, your code uses the undefined variable A
B = A' + A;
B(1:n+1:end)=diag(A); %This part is supposed to take any square matrix and turn it symmetrical, it wont be nessesary if I can accomplish this is the first part of code.
Typically the code would instead be
B = (A' + A)/2;
which has the advantage of leaving the values the same if the matrix was already symmetric. For example if A was ones(3,3) then your existing code would first create
B =
2 2 2
2 2 2
2 2 2
and then you would replace the diagonal to get
B =
1 2 2
2 1 2
2 2 1
which is a valid symmetric matrix, but the non-diagonal entries are now twice what they used to be.

Community Treasure Hunt

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

Start Hunting!

Translated by