在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
更多&回答...