MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

function com = combinations(n,k)
if k > n
error('Cannot calculate with given values')
end
com = factorial(n)/(factorial(k)*factorial(n-k));
end


If the combinations function receives invalid input, MATLAB stops execution
immediately after throwing the error message:


combinations(4,8)


Error using combinations (line 3)
Cannot calculate with given values


Add Run-Time Parameters to Your Warnings and Errors


To make your warning or error messages more specific, insert components of the
message at the time of execution. The warning function uses conversion characters that
are the same as those used by the sprintf function. Conversion characters act as
placeholders for substrings or values, unknown until the code executes.


For example, this warning uses %s and %d to mark where to insert the values of variables
arrayname and arraydims:


warning('Array %s has %d dimensions.',arrayname,arraydims)


If you execute this command with arrayname = 'A' and arraydims = 3, MATLAB
responds:


Warning: Array A has 3 dimensions.


Adding run-time parameters to your warnings and errors can clarify the problems within
a program. Consider the function combinations from “Throw Errors” on page 26-30.
You can throw a much more informative error using run-time parameters:


function com = combinations(n,k)
if k > n
error('Cannot choose %i from %i elements',k,n)
end
com = factorial(n)/(factorial(k)*factorial(n-k));
end


Issue Warnings and Errors
Free download pdf