フィルターのクリア

Using relational operator as a function input

3 ビュー (過去 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 Center および File ExchangeScope Variables and Generate Names についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by