Passing a function as an argument when the function itself has been passed
Info
This question is closed. Reopen it to edit or answer.
Show older comments
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?
Answers (4)
madhan ravi
on 11 May 2019
Edited: madhan ravi
on 11 May 2019
Using anonymous function:
f = @(x) exp(x);
g = @(x) sin(f(x));
h = @(x) 2*g(x);
h(1) % Evaluation
Sulaymon Eshkabilov
on 11 May 2019
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 Comment
madhan ravi
on 11 May 2019
Edited: madhan ravi
on 11 May 2019
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
on 11 May 2019
0 votes
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)))
Sulaymon Eshkabilov
on 11 May 2019
0 votes
Now you can verify this with any function.
This question is closed.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!