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

조회 수: 12 (최근 30일)
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.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 5월 10일
편집: Ameer Hamza 2020년 5월 10일
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
Umair Mughal
Umair Mughal 2020년 5월 10일
편집: Umair Mughal 2020년 5월 11일
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

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by