Using relational operator as a function input
12 次查看(过去 30 天)
显示 更早的评论
I do not know how to use relational operator as a function input.
For example, if I have to creat a function that recieves a condition like below, in which data represents a matrix of numbers
count_var(data < 0.2)
I don't know exactly how to pass down the relational operator < or any operators that will be passed down by the user
0 个评论
回答(2 个)
Sreelakshmi S.B
2019-3-7
If it’s the condition you want to pass, you could always pass it as a string or a character array and then parse it to get the relational operator.
You can also use function handles for this purpose by placing the condition you wish to pass inside a function.
For eg: if the condition you want to check is if a variable you pass is less than 3:
Define a function that checks this condition:
function out=condition_check(value)
%function to verify a condition(here to check if the passed value is less than 3)
out=0;
if(value<3)
out=1;
end
end
Now modify your function such that it takes a function handle as an input:
function your_function(condition,x)%condition is a function handle
%a trial function that prints yes if x satisfies the condition in the function pointed to by the 'condition' function handle and no if it doesn't
if(condition(x))
disp("yes");
else
disp("No");
end
end
Now you can call the function as follows:
your_function(@condition_check,10);%% replace 10 with your data point and @condition_check with the handle to whatever function contains the condition you want to check
0 个评论
Walter Roberson
2019-3-7
Each relational operation has a formal name that can be used with the @ operation
result = YourFunction(data, @le, 3)
function result = YourFunction(data, relation, threshold )
result = mean( relation(data, threshold ) )
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!