symmetric matrices using MATLAB

178 Views Asked by At

Write a Matlab function that takes a matrix and test if it is symmetric or not. The function will return the number "1" if the matrix is symmetric and "0" if it is not.

function B=symmet(A)

A = input("Enter a square Matrix");

[r, c]=size(A);

for i = 1:r

    for j = 1:c

        if i~=j

          if(A(i,j) == A(j,i))

            disp('1')

          else      

            disp('0')

          end

        end

    end

end
B
end

Now how I can define a function in MATLAB that answer my question. In which, just if I give this function any square matrix I receive only output 0 or 1 related to symmetry.

1

There are 1 best solutions below

0
On BEST ANSWER

You will instead want to initialize the variable to 1 (i.e., default as symmetric) to start and then switch it to 0 only if you find out the matrix is not symmetric.

So first open a new file and name it something like isSymmetric.m. This will generate a MATLAB script for you to use.

In the body, you define the function name at the top, which has to match your file name. You also define your return variable (called answer below).

function answer = isSymmetric(matrix)
  answer = 1;
  for i = 1:size(matrix,1) 
    for j= 1:size(matrix,2)
      if(A(i,j) != A(j,i))
        answer = 0;
        break;
      end
    end
    
    if (answer = 0)
      break;
    end
  end

Notice in the code, the function returns answer = 1 by default, and only changes answer = 0 if it runs into something non-symmetric.