Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-10, 16:49   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 是否可以为Matlab中的下标提供默认值?

在Matlab中,当尝试访问不存在的矩阵元素时,通常会引发错误:

>> month(0) ??? Subscript indices must either be real positive integers or logicals. 我想知道是否有一种功能可以在这种情况下提供默认值。例如,:

>> get_def(month(0), NaN) ans = NaN PS我可以解决这种特殊情况下标( 0 ),但我想知道更通用的方法。


回答:
没有内置的MATLAB函数可以执行所需的操作。您可以使用try-catch块:

>> try a = month(0); catch a = nan; end >> a a = NaN 然而,最好的办法可能是第一个错误检查的指标,抛出一个错误或设置为默认值的变量,如果它是超出范围。

如果您确实想尝试使用可能为0的索引,则可以编写自己的get_def函数。这是一种实现方法:

function value = get_def(vector,index,defaultValue) try value = vector(index); catch value = defaultValue; end end 然后,您可以通过以下方式使用此功能:

>> month = 1:12; >> get_def(month,0,nan) ans = NaN >> get_def(month,1,nan) ans = 1

更多&回答...
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 23:50


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.