![]() |
是否可以为Matlab中的下标提供默认值?
在Matlab中,当尝试访问不存在的矩阵元素时,通常会引发错误:
>> month(0) ??? Subscript indices must either be real positive integers or logicals. 我想知道是否有一种功能可以在这种情况下提供默认值。例如,: >> get_def(month(0), NaN) ans = NaN PS我可以解决这种特殊情况下标( 0 ),但我想知道更通用的方法。 回答: 没有内置的MATLAB函数可以执行所需的操作。您[I]可以[/I]使用[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/try.html"]try-catch[/URL]块: >> try a = month(0); catch a = nan; end >> a a = NaN 然而,最好的办法可能是[I]第一个[/I]错误检查的指标,抛出一个错误或设置为默认值的变量,如果它是超出范围。 如果您确实想尝试使用可能为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 [url=https://stackoverflow.com/questions/1272283]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 23:27。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.