I am having a bit of trouble with an nxn matrix problem.
The problem is: Write a user-defined MATLAB function that calculates the determinant of a square ( _n x n _ ) matrix, where n can be 2, 3, or 4. For function name and arguments, use D= Determinant(A). The input argument A is the matrix whose determinant is calculate. The function Determinant show first check if the matrix is a square. If it is not, the output D should be the message "The matrix must be square." Use Determinant to calculate the determinant of the following matrices.
It then goes on to give two different matrices, however, that is not what I need help with. My function is what is giving me difficulties. I entered the 3x3 matrix that I was given first, and came up with an error in the 34th line of my code saying that it was incomplete or incorrect. I have italicized this line to make it easier to find. Any help is greatly appreciated. Thank you!
Here is my code:
function D = Determinant( A )
[n m]=size(A);
if n ~= m
d ='ERROR'
disp('The matrix has to be square')
elseif n > 4
d ='ERROR'
disp('The matrix size cannot be larger than 4 by 4')
elseif n == 2
D=det2by2(A);
elseif n == 3
D=det3by3(A);
elseif n == 4
D=det4by4(A);
end
function D4 = det4by4( A )
Sa=A(2:4,2:4);
Sb=A(2:4,[1 3 4]);
Sc=A(2:4,[1 2 4]);
Sd=A(2:4,1:3);
_D4=A(1,1)*det3by3(Sa)-A(1,2)*det3by3(Sb)+A(1,3)*det3by3(Sc)-
A(1,4)*det3by3(Sd);_
function d3=det3by3(A)
S1=A(2:3,2:3);
S2=A(2:3,[1 3]);
S3=A(2:3,1:2);
d3=A(1,1)*det2by2(S1)-A(1,2)*det2by2(S2)+A(1,3)*det2by2(S3);
function d2=det2by2(B)
d2=B(1,1)*B(2,2)-B(1,2)*B(2,1);
end
end