pvkc
pvkc

Reputation: 89

Check if value is in returned value of function in MATLAB

I have a function that returns a single element in most cases. In a particular case it returns a vector. How to efficiently check if a given value is present in the returned value/values of the function.?

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

Upvotes: 1

Views: 93

Answers (2)

Chris Taylor
Chris Taylor

Reputation: 47392

I would probably use

ismember(value, array)

If you want it to be fast, the best thing to do is try alternative options and profile it. The best solution will depend on how often your function returns a vector as opposed to a scalar. Here are a couple of options:

// 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

You can turn the profiler on with profile on, run the function, and then look at the results with profile viewer. Alternatively you can do some simpler timings with tic and toc.

Upvotes: 2

Dan
Dan

Reputation: 45752

This is a very very vague question. do you mean this:

value = 5;
array = [1 5 4 6 7];

any(array==value)

Upvotes: 2

Related Questions