Matlab confuses variable with matrix

So I declare my function as: f=@(x) 54*(x^6) + 45*(x^5) - 102*(x^4) - 69*(x^3) + 35*(x^2) + 16*x - 4 and I get these errors:
Error using ^ (line 51)
Incorrect dimensions for raising a matrix to a power. Check that the matrix is square and the power is a scalar. To perform elementwise matrix powers, use '.^'.
Error in Bisection2>@(x)54*(x^6)+45*(x^5)-102*(x^4)-69*(x^3)+35*(x^2)+16*x-4 (line 6)
f=@(x) 54*(x^6) + 45*(x^5) - 102*(x^4) - 69*(x^3) + 35*(x^2) + 16*x - 4

回答(1 个)

Apparently, ‘x’ is a vector (or array). Use element-wise exponentiation (.^) in that event:
f=@(x) 54*(x.^6) + 45*(x.^5) - 102*(x.^4) - 69*(x.^3) + 35*(x.^2) + 16*x - 4
See: Array vs. Matrix Operations for an extended discussion.

3 个评论

I did that and now I get the same error for the ' * ' operator. I replaced the function with:
f=@(x) 54.*(x.^6) + 45.*(x.^5) - 102.*(x.^4) - 69.*(x.^3) + 35.*(x.^2) + 16.*x - 4;
because the error says so :Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To perform elementwise
multiplication, use '.*'.
However the error keeps coming up even after the .*
Your f is being passed a vector in a context where the surrounding code expects a scalar.
If you are writing typical bisection code you probably have something like
if f(a)*f(b) < 0
That code would be incorrect for the case where a and b are vectors.
I speculate that you are trying to keep track of all of the a and b values in vectors but forgot to index them to only get the current ones when you call f
@Walter — Thank you!
(There were no multiplications in the original Question.)

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by