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

조회 수: 1(최근 30일)
Paul 2022년 9월 27일
댓글: Paul 2022년 9월 27일
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

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23 2022년 9월 27일
편집: Stephen23 2022년 9월 27일
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표시숨기기 없음
Paul 2022년 9월 27일
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

댓글을 달려면 로그인하십시오.

범주

Find more on Startup and Shutdown 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!

Translated by