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

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.

 採用された回答

dpb
dpb 2018 年 8 月 22 日

0 投票

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
>>

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Type Conversion についてさらに検索

製品

リリース

R2018a

質問済み:

2018 年 8 月 22 日

回答済み:

dpb
2018 年 8 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by