How do I let the user enter an equation that is then able to be used in abs() calcualtions
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Colten
am 23 Jan. 2023
Kommentiert: Walter Roberson
am 23 Jan. 2023
I want the user to be able to enter a function that is then stored in y3 that I am able to use. I currently get an error with er=max(abs(y4-y3)); when i try and I and run it. I am able to make it work when I type the equation direcly into the code but not when getting from user input
x = 0:0.001:1;
fprintf(1,'For example: cos(x)\n');
s = input(' ', 's');
F = str2func(['@(x) ', s]);
y3 =F;
y4=x;
er=max(abs(y4-y3)); %maximum error
plot(x,y3);
title(['f(x) = ' s ' and Hermite interpolant, max. error is ' , num2str(er)]);
1 Kommentar
Walter Roberson
am 23 Jan. 2023
The code works for me when I use your input() instead of assigning a constant to s .
What problem do you observe?
It would be a problem if the user typed in a @() anonymous function definition instead of an expression. Or if the user expression does not include x
Akzeptierte Antwort
Sulaymon Eshkabilov
am 23 Jan. 2023
Use this small change by specifying the input argument (x) in your code:
x = 0:0.001:1;
fprintf(1,'For example: cos(x)\n');
s = input(' ', 's');
F = str2func(['@(x) ', s]);
y3 =F(x); % This is necessary
y4=x;
er=max(abs(y4-y3)); %maximum error
plot(x,y3);
title(['f(x) = ' s ' and Hermite interpolant, max. error is ' , num2str(er)]);
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Function Handles finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!