Converting sting to variable

1 回表示 (過去 30 日間)
Sachin Dighe
Sachin Dighe 2020 年 12 月 16 日
コメント済み: Sachin Dighe 2020 年 12 月 18 日
Hello everyone,
I am working on a matlab code.
I have a function in terms of x, say (x)^2 + x.
I want to find values of this function for different values of x, say from 1 to 5.
For that I am using a 'for' loop.
Example,
For x = 1 : 5
fx(x,1) = (x)^2 + x
End
But problem is that, this is not the only function. I want these values for any other functions of 'x', say cos(x), etc.
And I want this function to be given by a user as a sting in terms of 'x' either as an input in a cell or as input in inputbox and then I want to use this in 'for' loop.
This is like converting a string to function with variable as 'x'.
Please help me. How to do this.
Thank you in advance

採用された回答

David Hill
David Hill 2020 年 12 月 16 日
a='3*x.^2+2*x-5';%if you input your function to support arrays, then no for-loop is needed.
y=str2func(['@(x)',a]);
z=y(1:10);
  2 件のコメント
the cyclist
the cyclist 2020 年 12 月 16 日
... and you could use inputdlg to get the string from the user.
Sachin Dighe
Sachin Dighe 2020 年 12 月 18 日
Thank you, it is working. Now how to convert function back to number?

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by