MatLab:检查行向量中的整数时出错

 浪子一品香_938 发布于 2023-02-13 13:12

我使用MatLab为Horner的算法编写以下代码

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

我现在需要添加错误检查以确保调用者在行向量a中使用整数值.

对于我以前使用的整数检查

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

但这是一个单一的值,我不确定如何检查a中的每个元素.

1 个回答
  • 你有(至少)两个选择.

    1)使用any:

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

    或者更简洁......

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


    2)使用更强大的能力validateattributes:

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

    此功能也可以检查十几种其他内容.

    2023-02-13 13:15 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有