Convert a datatype (like string) into Simple Plain Text like a Matlab Function

13 views (last 30 days)
Well in programming we have datatypes that tells the compiler how to see the certain variable. And there are built-in functions imported from libraries, compiler see the whole list of functions (like sin, rand) and compile the behine the scene code.
So, if we have a string like "sin(x)", can we convert it into a simple text sin(x). So in this case instead of taking "sin(x)" as a string, compiler identifies it as a built-in function. In app Designer I want a plot a function that user can define from TextField using MATLAB programming, and the only solution I can think of this is that user can also access the MATLAB functions.
Alternatively, we can say can a user add an input as a MATLAB function, or maybe it could be like --> can we change the functions while the program running.

Accepted Answer

Ameer Hamza
Ameer Hamza on 10 May 2020
Edited: Ameer Hamza on 10 May 2020
See str2func(): https://www.mathworks.com/help/releases/R2020a/matlab/ref/str2func.html to convert the string to function handle.
For more advanced cases, see feval(): https://www.mathworks.com/help/releases/R2020a/matlab/ref/feval.html and eval(): https://www.mathworks.com/help/releases/R2020a/matlab/ref/eval.html. However, use them with care and also read this: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval to see that why using them can be a bad idea if used carelessly:
  2 Comments
Umair Mughal
Umair Mughal on 10 May 2020
Edited: Umair Mughal on 11 May 2020
Well thanks, I did it with str2func(); on web I was just missing the proper words for that, and that was easy...
function main(app)
s = app.SpeedEditField.Value; % Speed of Animation
[m1, m2] = Range(app);
x = m1:0.1:m2;
try
f = str2func(strcat('@(x)', app.FunctionEditField.Value));
y = f(x);
catch ME
uialert(app.UIFigure, ME.message, 'Function Error');
return;
end
h = animatedline(app.UIAxes);
for k = 1:s:length(x)-s-1
xvec = x(k:k+(s-1));
yvec = y(k:k+(s-1));
addpoints(h, xvec, yvec);
drawnow
end
return;
end

Sign in to comment.

More Answers (0)

Categories

Find more on Interactive Control and Callbacks 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!