如何在 MATLAB 中绘制具有两个变量的多项式作为曲面?
How to plot a polynomial with two variables as a surface in MATLAB?
我试过在 MATLAB 中绘制这个等式:
0.9486 - (1.0544*w0) + (0.8961*w1) + (w0*w1) + 1.1*(w0^2+w1^2)
w0 的值从 0 到 4,w1 的值从 -4 到 0
我需要在 MATLAB 中将其绘制为曲面,因此我编写了以下代码:
w0=(0:0.2:4); % y-axis
w1=(0:-0.2:-4); % x-axis
J=zeros(length(w0),length(w1)); % Matrix to be plotted on z-axis as a
surface
i=0; % indices for creating J
j=0; % indices for creating J
for w0=0:0.2:4
j=j+1;
i=i+1;
for w1=0:-0.2:-4
J(i,j)=0.9486-1.0544*w0+0.8961*w1+w0.*w1+1.1*(w0.*w0+w1.*w1);
% Equation to be implemented
end
end
w0=(0:0.2:4);
w1=(0:-0.2:-4);
%w0 and w1 created again as for loops reduced them to their
final value of 4 and -4.
mesh(w1,w0,J) %to create surface plot
ax = gca;
ax.XDir = 'reverse'; %reversing the axis as required in the task
虽然创建了表面,但矩阵 J 并未准确填充。它确实是 21x21,它应该是(w0 和 w1 都是 1x21 向量),但是 J 中的值只出现在对角线上,其余为零。
我不能将 w0 和 w1 作为索引,因为它们包含小数,并且像这样(在第一个 for 循环之后)将 i 和 j 作为索引是我可以获得 J 的 21x21 矩阵大小的唯一方法。
这是所需表面的图像:
这是我到目前为止能够绘制的表面图像:
任何人都可以帮助我正确填充 J 矩阵以便我可以重新创建正确的曲面吗?
我没有详细查看你的代码,但是
- 你应该用
.*
和.^
来代替element-wise operations(*
和^
是矩阵乘法和矩阵幂,所以不是你想要的) .
- 您可以使用 vectorization.
不使用循环来完成
这是我的做法。这利用了 implicit singleton expansion,它需要 Matlab R2016b 或更高版本:
w0=(0:0.2:4).'; % y-axis
w1=(0:-0.2:-4); % x-axis
J = 0.9486 - (1.0544.*w0) + (0.8961.*w1) + (w0.*w1) + 1.1*(w0.^2+w1.^2);
mesh(w1,w0,J)
xlabel w1
ylabel w0
ax = gca;
ax.XDir = 'reverse';
fsurf() 函数完成相同的工作。这是代码...
f1 = @(w0,w1) 0.9486 - (1.0544*w0) + (0.8961*w1) + (w0*w1) + 1.1*(w0^2+w1^2)
fsurf(f1, [0, 4, -4, 0])
产生如下表面:
我试过在 MATLAB 中绘制这个等式:
0.9486 - (1.0544*w0) + (0.8961*w1) + (w0*w1) + 1.1*(w0^2+w1^2)
w0 的值从 0 到 4,w1 的值从 -4 到 0
我需要在 MATLAB 中将其绘制为曲面,因此我编写了以下代码:
w0=(0:0.2:4); % y-axis
w1=(0:-0.2:-4); % x-axis
J=zeros(length(w0),length(w1)); % Matrix to be plotted on z-axis as a
surface
i=0; % indices for creating J
j=0; % indices for creating J
for w0=0:0.2:4
j=j+1;
i=i+1;
for w1=0:-0.2:-4
J(i,j)=0.9486-1.0544*w0+0.8961*w1+w0.*w1+1.1*(w0.*w0+w1.*w1);
% Equation to be implemented
end
end
w0=(0:0.2:4);
w1=(0:-0.2:-4);
%w0 and w1 created again as for loops reduced them to their
final value of 4 and -4.
mesh(w1,w0,J) %to create surface plot
ax = gca;
ax.XDir = 'reverse'; %reversing the axis as required in the task
虽然创建了表面,但矩阵 J 并未准确填充。它确实是 21x21,它应该是(w0 和 w1 都是 1x21 向量),但是 J 中的值只出现在对角线上,其余为零。
我不能将 w0 和 w1 作为索引,因为它们包含小数,并且像这样(在第一个 for 循环之后)将 i 和 j 作为索引是我可以获得 J 的 21x21 矩阵大小的唯一方法。
这是所需表面的图像:
这是我到目前为止能够绘制的表面图像:
任何人都可以帮助我正确填充 J 矩阵以便我可以重新创建正确的曲面吗?
我没有详细查看你的代码,但是
- 你应该用
.*
和.^
来代替element-wise operations(*
和^
是矩阵乘法和矩阵幂,所以不是你想要的) . - 您可以使用 vectorization. 不使用循环来完成
这是我的做法。这利用了 implicit singleton expansion,它需要 Matlab R2016b 或更高版本:
w0=(0:0.2:4).'; % y-axis
w1=(0:-0.2:-4); % x-axis
J = 0.9486 - (1.0544.*w0) + (0.8961.*w1) + (w0.*w1) + 1.1*(w0.^2+w1.^2);
mesh(w1,w0,J)
xlabel w1
ylabel w0
ax = gca;
ax.XDir = 'reverse';
fsurf() 函数完成相同的工作。这是代码...
f1 = @(w0,w1) 0.9486 - (1.0544*w0) + (0.8961*w1) + (w0*w1) + 1.1*(w0^2+w1^2)
fsurf(f1, [0, 4, -4, 0])
产生如下表面: