检查值是否在 MATLAB 中函数的返回值中



我有一个在大多数情况下返回单个元素的函数。在特定情况下,它返回一个向量。如何有效地检查给定值是否存在于函数的返回值中。?

for i=1:n
x=somefunc(data)
//now x could be single value or vector
//say k single value, k=5. 
if(k==x)  // This works if x is single value. What to do in case x is vector.?
//do something
end
// k value changes in every loop, so does x.
end

我可能会使用

ismember(value, array)

如果您希望它快速,最好的办法是尝试其他选项并对其进行分析。最佳解决方案将取决于函数返回向量而不是标量的频率。以下是几个选项:

// Use ismember on every iteration
if ismember(k, x)
  // do things
end
// Use any on every iteration
if any(k==x)
  // do thing
end
// Check if you have a scalar value, call ismember if not
if isscalar(x) && k==x || ismember(k,x)
  // do things
end
// Check if you have a scalar value, call any if not
if isscalar(x) && k==x || any(k==x)
  // do things
end

您可以使用 profile on 打开探查器,运行该函数,然后使用 profile viewer 查看结果。或者,您可以使用 tictoc 进行一些更简单的计时。

这是一个非常非常模糊的问题。 你的意思是:

value = 5;
array = [1 5 4 6 7];
any(array==value)

最新更新