how take a mathematical function from user
1 view (last 30 days)
Show older comments
here in my code it is me who write F and G function in my Scrip File . now i want the user to enter the F and G in Command Window so i can use as argument in function like euler_forward without witting F and G in my File Script
% Script file: main1.m
f=@(x,y) x./y;
% Calculate exact solution
g=@(x) sqrt(x.^2+1);
xe=[0:0.01:0.3];
ye=g(xe);
% Call functions
[x1,y1]=euler_forward(f,0,1,0.3,6);
[x2,y2]=euler_modified(f,0,1,0.3,6);
[x3,y3]=euler_backward(f,0,1,0.3,6);
% Plot
plot(xe,ye,x1,y1,x2,y2,x3,y3,)
xlabel('x')
ylabel('y')
legend('Analytical','Forward','Modified','Backward')
axis([0 0.3 1 1.07])
0 Comments
Answers (1)
Star Strider
on 8 May 2021
prompt = {'Enter f(x,y):', 'Enter g(x):'};
response = inputdlg(prompt)
f = str2func(['@(x,y)', vectorize(response{1})])
g = str2func(['@(x)', vectorize(response{2})])
Entering the two functions in your questions produces —
response =
2×1 cell array
{'x/y' }
{'sqrt(x^2+1)'}
f =
function_handle with value:
@(x,y)x./y
g =
function_handle with value:
@(x)sqrt(x.^2+1)
Note — If the user entering the functions understands the requirement that they must be vectorized, vectorize them while entering them, and delete the vectorize call. (The vectorize function has its critics, however it can be appropriate here, and makes life easier.. It is straightforward to write a similar function to do the same thing, however as long as it exists, use it.)
.
0 Comments
See Also
Categories
Find more on Line Plots 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!