Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

TASK 2 OBJECTIVE: Write a function to check whether a 2-D matrix is a magic squa

ID: 3726758 • Letter: T

Question

TASK 2 OBJECTIVE: Write a function to check whether a 2-D matrix is a magic square. The MATLAB function magic(N) constructs an N×N magic square. magic(3) ans = 3 5 7 The "magical" property of a magic square is that it contains the integers 1 to N2 exactly once each and every row, column, and diagonal has the same sum 841+6-15 3+5+7-15 4+9+2-15 8+3+4=15 1+5+9=15 6+7+2=15 8+5+2-15 6+5+4-15 Now it's your turn. Write a function (verifv magic.m) that take as input a square matrix anc computes the sum of each row, column, and diagonal of the matrix to determine whether the input is a magic square. If the input is not a square matrix, use the error function to display an error message and abort the function. The output of the function should be a logical value indicating whether or not the input is a magic square: logical true for a magic square, logical false for a muggle square. Example: >> verify magicímagic(3)) ans = >> verify magiclf1 2 3;456;789]) ans = 0

Explanation / Answer

function [flag] = verify_magic(arr)

    % get the dimensions of array

    [r, c] = size( arr );

    % store the sum of diagonal

    diag1 = 0;

   

    for i = 1 : r

       

       diag1 = diag1 + arr( i , i );

       

    end

   

    diag2 = 0;

   

    % find the sum of secons diagonal

    for i = r : -1 : 1

       

       diag2 = diag2 + arr( i , i );

       

    end

   

    % if the two diagonals are not equal

    if diag1 ~= diag2

     

        flag = false;

       

        return;

       

    end

   

    for i = 1 : r

       

        sum = 0;

       

        for j = 1 : c

           

            sum = sum + arr( i , j );

           

        end

       

        % if the sum of the current column is not same

        % as the sum of diagonal

        if sum ~= diag1

           

            flag = false;

       

            return;

           

        end

       

    end

   

   

    for i = 1 : r

       

        sum = 0;

       

        for j = 1 : c

           

            sum = sum + arr( j , i );

           

        end

       

        % if the sum of the current column is not same

        % as the sum of diagonal

        if sum ~= diag1

           

            flag = false;

       

            return;

            

        end

       

    end

   

    flag = true;

   

end