Passing a function as an argument when the function itself has been passed
情報
この質問は閉じられています。 編集または回答するには再度開いてください。
古いコメントを表示
What I need to do is the following. I have some functions f, g, and h. Now I want to pass function f to g. To do this, I write
g(@f)
So my function g gets as an argument my function f. Inside function g, I call function h, and I want to pass f as an argument. So, my function g looks kind of like
function [y] = g(x)
h(@x)
end
and my function h looks like
function [y] = h(x)
x(0.5)
end
However, I am not allowed to write h(@x) inside the function g, as I get the error message ""x" was previously used as a variable, conflicting with its use here as the name of a function or command."
On the other hand, if I write h(x) inside the function g, then I get the error message "Array indices must be positive integers or logical values." since the x in the function h is not interpreted as a function anymore. So how can I make this work, how can I pass a function twice?
0 件のコメント
回答 (4 件)
madhan ravi
2019 年 5 月 11 日
編集済み: madhan ravi
2019 年 5 月 11 日
Using anonymous function:
f = @(x) exp(x);
g = @(x) sin(f(x));
h = @(x) 2*g(x);
h(1) % Evaluation
0 件のコメント
Sulaymon Eshkabilov
2019 年 5 月 11 日
If I have undertood your problem correctly, what you are trying to do is g(h(f(x))), right?!
In other words, to pass f(x) into h function as its argument and h into g function as its argument.
f = @(x) exp(x); % E.g. f = exp(x); or can be any function or math expression with a variable x or x, y, z
g = @(f)(sin(f)); % E.g. g = sin(exp(x))
h = @(g)(2*g); % E.g. h = 2*sin(exp(x))
1 件のコメント
madhan ravi
2019 年 5 月 11 日
編集済み: madhan ravi
2019 年 5 月 11 日
What?
Verify the results
For instance
2*sin(exp(1)) %and h(1) % your way see if both the results are same. Hint: No.
Sulaymon Eshkabilov
2019 年 5 月 11 日
0 投票
You are using a wrong command what I have proposed. The correct way of calling the anounymous function in my proposed solution is: h(g(f(1)))
0 件のコメント
この質問は閉じられています。
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!