MATLAB: Help with nxn matrices

matricesnxn matrix

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 3×3 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 )
% The function calculates the determinant of an nxn matrix A,
% where n can be 2, 3, or 4.
[n m]=size(A); % n= # of rows in A, m= # of columns in A
if n ~= m % check if A is a square matrix
d ='ERROR' % if not, display error message
disp('The matrix has to be square')
elseif n > 4 % otherwise, check if A is larger than 4x4
d ='ERROR' % if so, display error message
disp('The matrix size cannot be larger than 4 by 4')
elseif n == 2 % otherwise, check if A is 2x2
D=det2by2(A); % if so, call the subfunction for a 2x2 determinant
elseif n == 3 % otherwise, check if A is 3x3
D=det3by3(A); % if so, call the subfunction for a 3x3 determinant
elseif n == 4 % otherwise, check if A is 4x4
D=det4by4(A); % if so, call the subfunction for a 4x4 determinant
end % end the program
%Subfunctions
function D4 = det4by4( A )
% The function calculates the determinant of a 4 by 4 matrix.
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)
%
% Evaluating the determinant by expanding using the first row
%
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);
%
% Subfunction
%
function d2=det2by2(B)
d2=B(1,1)*B(2,2)-B(1,2)*B(2,1);
end
end

Best Answer

The only problem I find is the two ending end. After adding end to the end of each function. (You don't say what kind of trouble you see.)
>> A = rand(4);
>> det(A)
ans =
-0.0261
>> D = Determinant( A )
D =
-0.0261
&nbsp
Addendum in response to comment.
>> A=[1 5 4; 2 3 6; 1 1 1]
>> D = Determinant( A )
D =
13
>> det(A)
ans =
13
>>
where my version of your function, Determinant, is attached. I have added an end to the end of each function. Either all functions should be closed with end or none.