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!

 Réponse acceptée

Star Strider
Star Strider le 10 Sep 2020
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 commentaires

Thank you!
Star Strider
Star Strider le 10 Sep 2020
As always, my pleasure!
Steven Lord
Steven Lord le 10 Sep 2020
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 le 10 Sep 2020
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Function Creation dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by