Hi
Is there any way i can transform 2*x^4+3x-4 into 2.*x.^4+3.*x-4 in a script? Without typing it in manually.
Thanks!

 採用された回答

Star Strider
Star Strider 2020 年 9 月 10 日

0 投票

Include all the operators, and use the vectorize function:
y = str2func(['@(x)' vectorize('2*x^4+3*x-4')]) % Vectorize & (Optionally) Create Anonymous Function
producing:
y =
function_handle with value:
@(x)2.*x.^4+3.*x-4
The documentation states that vectorize is not recommended, however gives no alternative function or approach. I have no idea what the reason is for this, since vectorize can be useful for creating string expressions as anonymous functions.

4 件のコメント

Kristoffer Søhagen
Kristoffer Søhagen 2020 年 9 月 10 日
Thank you!
Star Strider
Star Strider 2020 年 9 月 10 日
As always, my pleasure!
Steven Lord
Steven Lord 2020 年 9 月 10 日
I'm not 100% sure offhand of the reason it's listed in the documentation as not recommended. When used with str2func I'd say it's okay. But str2func wasn't always able to create anonymous functions and so vectorize was instead used with eval or inline. It's those interactions that I think should be discouraged (and I think was responsible for getting this function listed as not recommended), though less because of vectorize than the other two functions.
Star Strider
Star Strider 2020 年 9 月 10 日
Steven — Thank you!
When required, I use vectorize in my Answers (usually along with str2func) to do essentially what I did here. I got the sinking sensation that vectorize was in danger of being deprecated, and I plea for it to remain alive! It can be extraordinarily useful. I wasn’t aware that str2func could not always create anonymous functions, since I’ve only been using it for a few years, and almost always with Answers. .
I definitely agree with you with respect to eval and inline.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeFunction Creation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by