Using relational operator as a function input

조회 수: 2 (최근 30일)
Andrew Yoon
Andrew Yoon 2019년 3월 3일
답변: Walter Roberson 2019년 3월 7일
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

답변 (2개)

Sreelakshmi S.B
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

Walter Roberson
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 ) )

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by