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 个)
Star Strider
2019-12-15
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
3 个评论
Christina Mil
2019-12-15
Walter Roberson
2019-12-15
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
Star Strider
2019-12-15
@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!