Hi,
I have this code:
string='int(x^2,x)';
y=str2func(['@(x)' string]);
Then I try to plot it with fplot
fplot(y)
But the problem is that axes remain white, without an error or anything else.
I've already solved the problem with symbolic toolbox
syms y(x)
y(x)=eval(string)
fplot(y)
But this solution is terribly slow and for the application that I'm developping it is important a solution as fast as possibile. If I use str2func with functions that require only one input (cos,sin,...) it works perfectly but with function with 2 or more input axes remain white. Have you a solution to suggest me? Thanks in advance.

 採用された回答

Star Strider
Star Strider 2019 年 2 月 25 日

0 投票

Using str2func is not the correct approach for dealing with symbolic expressions, and especially those that involve symbolic functions (such as int) that only operate in the symbolic context.
Try this instead:
string = 'int(x^2,x)';
y = matlabFunction(str2sym(string))
fplot(y)
That is still significantly inefficient, however it has the one redeeming feature of producing the result you apparently want, using the character vector you began with.

4 件のコメント

Federico Spada
Federico Spada 2019 年 2 月 25 日
It is definitly faster but now I have another problem to overcome: if
string='1';
I have the same problem as before: axes remain white while i would want a line in y=1. Is there a way to fix this? Thanks
Star Strider
Star Strider 2019 年 2 月 25 日
That may also throw a ‘Too many input arguments’ error, and will require an if block to trap it.
This works:
string = '1';
y = matlabFunction(str2sym(string))
if nargin(y) < 1
fplot(@(x)y())
else
fplot(y)
end
Experiment to get the result you want with your functions.
Federico Spada
Federico Spada 2019 年 2 月 25 日
Ok, perfect! Thank you!
Star Strider
Star Strider 2019 年 2 月 25 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

製品

リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by