Why do I receive and error message for the negative in my function?

I am trying to input a function but everytime I run my script the negative on the first x gets an error mesage that says invalid use of an operator. I am not sure how else to rewrite the function so that the x is still negative.
g = @ -x.^3 + 4*x.^2 - 3

답변 (1개)

Dyuman Joshi
Dyuman Joshi 2023년 9월 11일
편집: Dyuman Joshi 2023년 9월 11일
The syntax for defining anonymous functions is -
f = @(list_of_independent_variables) relation_of_indepent_variables;
So for your case, it would be -
g = @(x) -x.^3 + 4*x.^2 - 3;
And to find the value of the function for a particular value, just plug it into the handle -
g(-3)
ans = 60
g(6.9)
ans = -141.0690

댓글 수: 3

Oh so my main problem was not having the (x) after the @ symbol not necessarily the fact that the variable was negative?
"Oh so my main problem was not having the (x) after the @ symbol not necessarily the fact that the variable was negative?"
Correct. See:
g = @x.^3 + 4*x.^2 - 3
would not be a syntax error. It would mean to take the handle to a function named x and to attempt to cube the function handle. You cannot do mathematics on a function handle so you would get a runtime error... but not a syntax error.

댓글을 달려면 로그인하십시오.

카테고리

태그

질문:

2023년 9월 11일

편집:

2023년 9월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by