-1

My goal is to have code that flags true if I give it a matrix that isn't a square and flags false if it is a square.

My code works correctly when I give it a non-square matrix. However it gives me an error when I give it a square matrix?

How could I fix my code?

function [flag] = checkSing(A) 

if det(A) == 0%if matrix is a square
    flag = 1;
elseif det(A) ~=0
    flag = 0;
end

end

This is the error message I recieved.

EDU>> A = [1 2; 3 4; 5 6];
EDU>> B = checkSing(A)
Error using det
Matrix must be square.

Error in checkSing (line 12)
if det(A) == 0%if matrix is a square
kal
  • 37
  • 2
  • 14

1 Answers1

1

You're supposed to check the dimensions of A to make sure it's square. Simply checking what output det(A) gives you doesn't check if the matrix is square. You're checking what the determinant output is... not the fact that the matrix is square. In fact, the function requires that the matrix be square and that's why you're getting that error.... your error checks don't work.

As such, if you want to check if the matrix isn't square, simply check to see if the number of rows is not equal to the number of columns:

function [flag] = checkSing(A) 
    flag = size(A,1) ~= size(A,2);
end

This returns a flag where it's true if the number of rows is not equal to the number of columns.


Minor Note

I don't think you're describing your problem properly.... your function's name is called checkSing... which I'm assuming you mean that you want to check if the matrix is singular. If that's the case, then checking to see if the determinant is zero is the definition of the matrix being singular. Is that what you really want instead? If so, then you need to modify this code so that it checks if the matrix is square too.

Something like this will work:

function [flag] = checkSing(A) 
    if size(A,1) == size(A,2) %// If matrix is square...
        flag = det(A) == 0; %// Flag is returned that checks if matrix is singular
    else
        flag = 1; %// Matrix isn't square, so return true anyway
    end
end
rayryeng
  • 102,964
  • 22
  • 184
  • 193