how many times to divide by zero? function in matlab

To check how many times a divide by zero error occurs for a given function in MATLAB, you can incorporate error handling using the try-catch statement.

For example, let's say you have a function called myFunction that performs a division operation:

main.m
function result = myFunction(a,b)
    result = a/b;
end
56 chars
4 lines

To handle the divide by zero error, you can modify the function as follows:

main.m
function result = myFunction(a,b)
    try
        result = a/b;
    catch ME
        if strcmp(ME.identifier,'MATLAB:divideByZero')
            fprintf('A divide by zero error occurred!\n');
        end
        rethrow(ME);
    end
end
236 chars
11 lines

The try block attempts to perform the division operation, while the catch block checks if the error thrown is a divide by zero error. If so, it prints a message to inform you that the error occurred. The rethrow statement rethrows the error so that any higher level error handling can take place.

To count the number of times a divide by zero error occurs, you can modify the catch block as follows:

main.m
function result = myFunction(a,b)
    numDivideByZeroErrors = 0;
    try
        result = a/b;
    catch ME
        if strcmp(ME.identifier,'MATLAB:divideByZero')
            numDivideByZeroErrors = numDivideByZeroErrors + 1;
        end
        rethrow(ME);
    end
end
271 chars
12 lines

This code initializes a variable numDivideByZeroErrors to zero before attempting the division operation. If a divide by zero error occurs, the variable is incremented. Once the function has run its course, the variable contains the total number of divide by zero errors that occurred.

gistlibby LogSnag