简体   繁体   English

如何评估具有不同x和y向量的两个变量的函数

[英]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 .) (您可以交换xy的顺序,具体取决于您是否希望沿z的行或列使用每个变量。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 计算百分位数? (或更笼统地说,在许多值z处由2个向量x和y隐式定义评估函数) - Calculate percentiles? (Or more generally, evaluate function implicitly defined by 2 vectors x and y at many values z) 两个向量x和y。 如何指向y中的最大元素并选择x中的相应元素? - Two vectors x and y. How do I point to the maximum element in y and pick its corresponding element in x? 如何从循环中存储两个变量(xy)? - How to store two variables (x.y) from a loop? 如何将两个不同长度的向量相乘 - How to multiply two vectors with different length 如何将x的值相同但y的值不同的两个散点相加? - How do I add up two scatter points with the same values of x but different values of y? 给定X,Y和Z向量生成轮廓 - Generate Contour Given X, Y and Z vectors 重复x和y向量以与scatter3()一起使用 - Repeating x and y vectors for use with scatter3() 在MATLAB中使用对数刻度上的3个向量和x,y向量创建等高线图 - Create a contour plot in MATLAB with 3 vectors and x, y vectors on a logarithmic scale 绘制两个不同的图(y轴),在matlab中共享相同的x - Plotting two different plots(y axes), sharing the same x in matlab MATLAB:如何在输入向量的所有可能组合上评估具有多个输入的函数 - MATLAB: How to evaluate a function with multiple inputs on all possible combinations of input vectors
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM