6 hump camel function - What is wrong with the code?

조회 수: 4 (최근 30일)
Mohammed Muaaz Hussain
Mohammed Muaaz Hussain 2019년 5월 30일
댓글: Mohammed Muaaz Hussain 2019년 5월 31일
Hello,
I am trying to plot the 6 hump camel back function using a simple code as shown below:
[x,y]=meshgrid(-2:0.02:2,-1:0.01:1);
z=((4-(2.1*(x.^2))+((x.^4)/3))*(x.^2))+(x.*y.*1)+(4*(-1+(y.^2))*(y.^2));
mesh(x,y,z)
A plot is made but it does not match the actual function at all. The term (x.*y.*1) was written so since an error was observed when I dropped the *1 (Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters.). How do I correct this?

채택된 답변

Guillaume
Guillaume 2019년 5월 30일
편집: Guillaume 2019년 5월 30일
The overuse of unnecessary brackets and the lack of any spacing make your expression very hard to read.
Multiplying by 1 will never change the result and will never make any difference to any error.
Your expression, without all the unnecessary brackets and with some spacing:
z = (4 - 2.1*x.^2 + x.^4/3)*x.^2 + x.*y + 4*(-1 + y.^2)*y.^2;
In my opinion much easier to read, and you can immediately see the two errors. You're doing matrix multiplication with x.^2 and y.^2 instead of element-wise multiplication. Changing the two * into .* is probably what you want:
z = (4 - 2.1*x.^2 + x.^4/3).*x.^2 + x.*y + 4*(-1 + y.^2).*y.^2;

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by