Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MatLab: Error checking for integers in a row vector

Tags:

matlab

I have used MatLab to write the following code for Horner's Algorithm

function [answer ] = Simple( a,x )
%Simple takes two arguments that are in order and returns the value of the
%polynomial p(x). Simple is called by typing Simple(a,x)
% a is a row vector
%x is the associated scalar value
n=length(a);
result=a(n);
for j=n-1:-1:1 %for loop working backwards through the vector a  
   result=x*result+a(j);
end
answer=result;
end

I now need to add an error check to ensure the caller uses integer values in the row vector a.

For previous integer checks I have used

if(n~=floor(n))
    error(...

But this was for a single value, I am unsure how to do this check for each of the elements in a.

like image 290
user3058633 Avatar asked Dec 02 '25 05:12

user3058633


2 Answers

You've got (at least) two options.

1) Use any:

if (any(n ~= floor(n)))
  error('Bummer. At least one wasn''t an integer.')
end

Or even more succinctly...

assert(all(n == floor(n)), 'Bummer. At least one wasn''t an integer.')


2) Use the much more capable validateattributes:

validateattributes(n, {'double'}, {'integer'})

This function can check for more than a dozen other things, too.

like image 56
Jeff Mather Avatar answered Dec 04 '25 00:12

Jeff Mather


Same math will work, but is now checking each element. Try this:

if any(n~=floor(n))
    error(...
like image 42
Pursuit Avatar answered Dec 04 '25 00:12

Pursuit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!