Matlab confuses variable with matrix

조회 수: 10 (최근 30일)
Christina Mil
Christina Mil 2019년 12월 15일
댓글: Star Strider 2019년 12월 15일
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
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
See: Array vs. Matrix Operations for an extended discussion.
  댓글 수: 3
Walter Roberson
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
Star Strider 2019년 12월 15일
@Walter — Thank you!
(There were no multiplications in the original Question.)

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by