Setting requirements for matrix and vector inputs into function and generating error message
Show older comments
For my homework I have been asked to create a function that solves systems of linear equations Ax = b for x.
I did this simply using x = A\b.
However, the function should test if A is a square matrix and if the size of the vector b matches the size of the matrix.
Furthermore if these conditions are not satisfied the function should display an error message.
I've tried a few methods using if, else etc. I have specifically tried:
if size(A,1)==size(A,2) && size(A,1)=size(b,1) && size(b,2)==1
but I do not know if I'm using this correctly? Or even if it is the correct thing to use?
I was just wondering what the best way of setting these conditions would be? And generating a custom error message if they are not met?
Any help would be greatly appreciated.
1 Comment
doc error % for error handling basics...
The if tests above are certainly the type of things you need to check, yes. There are a bunch of builtin functions beginning with is that you can look at for "the Matlab way" to test for certain things amongst which area couple of direct interest here in whether the solution vector is, in fact a vector and it's orientation.
"Square" isn't one supplied but following the lead of these might lead to a neatly packaged solution, maybe??? (Hint, hint... :) )
Most, if not all, of these functions are builtin rather than m-files so their m-files are empty excepting for the help text, but it's certainly possible to incorporate some additions as user m-files which provide "syntactic sugar" of making higher-level code using them much more succinct a readable.
ADDENDUM
NB: The snippet
if size(A,1)==size(A,2)
as written won't do what you think/want, however. Check out the help file for if carefully on behavior in Matlab...a small addition to what you've got will be required to get the answer you're expecting here.
Answers (1)
function y = fun(x)
% My custom function
assert(isnumeric(x),'Input x is not numeric')
assert(isscalar(s),'Input x must be scalar')
%
y = sqrt(x);
end
Tip: keep the conditions for each assert simple. Then you can write a clear error message for each assert.
If the conditions are complex, then calculate them before the assert:
tmp = ismatrix(x) && diff(size(x))==0 && size(x,1)>3;
assert(tmp,'Input x must be a square matrix larger than 3x3')
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!