Converts a string into a function to plot
조회 수: 6 (최근 30일)
이전 댓글 표시
So I have mathematic functions like sin(x), cos(x) etc. in a string format that I want to convert into a function so I would be able to plot it.
equ='sin(x)';
f= @(x) equ;
plot(x,f)
error message:
Error using plot
Invalid data argument.
댓글 수: 2
Stephen23
2020년 9월 4일
편집: Stephen23
2020년 9월 4일
"So I have mathematic functions like sin(x), cos(x) etc. in a string format that I want to convert into a function..."
Your example contains no strings or character arrays at all:
equ=sin(x);
f= @(x) equ;
This makes your question difficult to interpret. Do you actually have a character vector? E.g.:
str = 'sin';
Please show the actual definition of your input data.
채택된 답변
Stephen23
2020년 9월 4일
편집: Stephen23
2020년 9월 4일
>> equ = 'sin(x)';
>> fun = str2func(sprintf('@(x)%s',equ));
>> fun(pi/2)
ans =
1
댓글 수: 6
Stephen23
2020년 9월 4일
편집: Stephen23
2020년 9월 4일
"it does work when you only use it like you did fun(pi/2) but it somehow doesn't let me plot it."
I have no problems plotting it. As you did not show your code I have no way to debug what you tried.
"...but still cannot plot the graph. I still get the same error when try to plot it."
Not only is your code a secret, so is the error message that you get. No information -> no debugging help.
Well, it works for me. Lets try it together using two different plotting commands:
>> equ = 'sin(x)';
>> fun = str2func(sprintf('@(x)%s',equ));
>> X = linspace(-2*pi,2*pi,101);
>> Y = fun(X);
>> plot(X,Y)

>> ezplot(fun)

추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Title에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!