Converting a string containing a function (t) to a useable variable.

1 view (last 30 days)
I'm using inputdlg to take user input and calculate and store the value.
This is what I was trying to do.
x = inputdlg('Enter Mathematical Equation')
t = [0:0.001:20]
z = str2double (x{1})
I need to be able to enter 20*cos(4*t) for instance and have the calculated result stored in the variable, but I can't seem to get any result or for matlab to recognize the variable entered even if its declared prior to the inputdlg. Simply arguments like 20*cos(20) properly converts and calculates. How would I go on about being able to use the function from the string.

Accepted Answer

dpb
dpb on 22 Aug 2018
Need to convert string to the function---
>> t=0:pi/8:pi; % predefined t
>> s='20*cos(4*t)'; % sample input string
>> s=vectorize(['@(t)' s]) % convert to allowable functional form and vectorize expression
s =
'@(t)20.*cos(4.*t)'
>> fn=str2func(s) % now create the function handle variable
fn =
function_handle with value:
@(t)20.*cos(4.*t)
>>
>> z=fn(t) % use it with existing t
z =
20.0000 0.0000 -20.0000 -0.0000 20.0000 0.0000 -20.0000 -0.0000 20.0000
>> fn(0) % or with some other input, constant or variable ok...
ans =
20
>>

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!