Alen
Alen

Reputation: 1788

MATLAB - Convert string to mathematical function

I'm trying to make application in Matlab which will take user input as string, convert it to mathematical function and plot it.

Problem is, I don't know how to convert string to math function. This is what I have tried:

f = get(handles.edit1, 'string');
n=0:length(f)-1;
func = str2func(f);
plot(n,func);

So if user inputs sin(x) it should be ploted.

Upvotes: 0

Views: 1229

Answers (3)

Alen
Alen

Reputation: 1788

I solved my problem by using ezplot:

f = get(handles.edit1, 'string');
ezplot(f)

This code can plot any y(x) function.

Upvotes: 0

Haider
Haider

Reputation: 341

Use eval

f = get(handles.edit1, 'string');
n=0:10;
plot(n,eval(f));

Upvotes: 0

mhmsa
mhmsa

Reputation: 475

normally you need to specify the values at which you plot the function if that's not an issue then I would replace plot with ezplot

also assuming the function takes only one variable

f = get(handles.edit1, 'string');
a = strfind(f,'(')-1;
func = str2func(f(1:a));
ezplot(func)

if you need a range of values to plot the function at i would use fplot instead

fplot(func,limits)

Upvotes: 3

Related Questions