简体   繁体   中英

How to evaluate function of two variables with different x and y vectors

I've been trying to evaluate a function in 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.

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?

See MATLAB's linspace function.

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,

y = linspace(x1,x2,n) generates n points. The spacing between the points is (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. As @obchardon pointed out, you can use meshgrid to make that 2D grid of x and y points to generate a matrix of 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 .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM