Using relational operator as a function input

12 visualizaciones (últimos 30 días)
Andrew Yoon
Andrew Yoon el 3 de Mzo. de 2019
Respondida: Walter Roberson el 7 de Mzo. de 2019
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

Respuestas (2)

Sreelakshmi S.B
Sreelakshmi S.B el 7 de Mzo. de 2019
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 el 7 de Mzo. de 2019
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 ) )

Categorías

Más información sobre Environment and Settings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by