Multiplying a polynomial with a vector.

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!

 采纳的回答

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 个评论

As always, my pleasure!
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.
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 Exchange 中查找有关 Function Creation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by