[英]How to evaluate function of two variables with different x and y vectors
I've been trying to evaluate a function in matlab. 我一直在尝试评估matlab中的函数。 I want my x vector to go from 0 to 1000 and my y vector to go from 0 to 125. They should both have a length of 101. The equation to be evaluated is z(x,y) = a y + b x, with a=10 and b=20. 我希望我的x向量从0到1000,我的y向量从0到125。它们的长度都应为101。要计算的方程为z(x,y)= a y + b x,其中a = 10和b = 20。
a = 10;
b = 20;
n = 101;
dx = 10; % Interval length
dy = 1.25;
x = zeros(1,n);
y = zeros(1,n);
z = zeros(n,n);
for i = 1:n;
x(i) = dx*(i-1);
y(i) = dy*(i-1);
for j = 1:n;
z(i,j) = a*dy*(j-1) + b*dx*(j-1);
end
end
I get an answer, but I don't know if I did it correctly with the indices in the nested for loop? 我得到一个答案,但是我不知道我是否正确使用嵌套的for循环中的索引来正确执行此操作?
See MATLAB's linspace function. 请参见MATLAB的linspace函数。
a=10;
b=20;
n=101;
x=linspace(0,1000,n);
y=linspace(0,125,n);
z=a*y+b*x;
This is easier and takes care of the interval spacing for you. 这更容易,并为您照顾间隔间隔。 From the linspace documentation, 从linspace文档中,
y = linspace(x1,x2,n) generates n points. y = linspace(x1,x2,n)生成n个点。 The spacing between the points is (x2-x1)/(n-1). 点之间的间距为(x2-x1)/(n-1)。
Edit: As others have pointed out, my solution above makes a vector, not a matrix which the OP seems to want. 编辑:正如其他人指出的那样,我上面的解决方案是一个向量,而不是OP似乎想要的矩阵。 As @obchardon pointed out, you can use meshgrid
to make that 2D grid of x and y points to generate a matrix of z. 正如@obchardon指出的那样,您可以使用meshgrid
制作x和y点的2D网格以生成z矩阵。 Updated approached would be: 更新的方法将是:
a=10;
b=20;
n=101;
x=linspace(0,1000,n);
y=linspace(0,125,n);
[X,Y] = meshgrid(x,y);
z=a*Y+b*X;
(you may swap the order of x
and y
depending on if you want each variable along the row or column of z
.) (您可以交换x
和y
的顺序,具体取决于您是否希望沿z
的行或列使用每个变量。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.