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

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 Exchange에서 Function Creation에 대해 자세히 알아보기

질문:

2020년 9월 10일

댓글:

2020년 9월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by