I want to enter a mathematical function as an argument to a function

1 view (last 30 days)
Hello, to be more precise: I want to call in my program a function that I have created and that allows to display the plot of a mathematical function, so I want to enter in argument of this function a mathematical expression that can be for example "sin(t) or 4*t+9". Knowing that the interval "t" is defined inside the function.
My problem is the following, when I launch the program it says to me that it does not know "t", logic since at the moment or the program reads it it is not yet defined.
How to solve this problem?
main program
plot_compare(sin(t) , 5 ,20);
secondary program
function plot_compare(f,N,M)
t = [];
S_N = [];
t = linspace(-pi ,pi ,M);
b = linspace (0,10,N);
S_N = sinesum(t,b);
plot(t,f,t,S_N);
end

Accepted Answer

Stephen23
Stephen23 on 27 Sep 2022
Edited: Stephen23 on 27 Sep 2022
The simple approach using a function handle:
plot_compare(@sin , 5 ,20);
plot_compare(@(t) 4*t+9 , 5 ,20);
function plot_compare(fnh,N,M)
t = linspace(-pi ,pi ,M);
b = linspace (0,10,N);
%S_N = sinesum(t,b);
plot(t,fnh(t));
end
  1 Comment
Paul
Paul on 27 Sep 2022
Thank you
I had found the beginning of a solution on the internet with the handle function but I understood where my mistake was, I must specify in the plot function that my function "f" must be plotted as a function of "t" so it's
plot(t,f(t))
and not
plot (t,f)
Thank you again

Sign in to comment.

More Answers (0)

Categories

Find more on Animation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!