# relation between two variable

7 views (last 30 days)
Li Chng on 2 Mar 2020
Answered: Image Analyst on 2 Mar 2020
if Z = f(X,Y)
if my raw data are the following,
X | Y | Z
11 | 13 | 14
8 | 15 | 15
6| 17 | 16
3 | 19 | 14
1 | 22 | 14
How to plot Z = f(X,Y) and subsequently find the function e.g Z = aX^2 + bY^2 + cXY + dX + eY + f?

Rik on 2 Mar 2020
You can plot a 3D scatter plot with scatter3.
To get your function you will need more points. You will need at least the same number of points as unknown variables.
Li Chng on 2 Mar 2020
Hi Rik.
Let say if i have 1000 points for X Y Z. Which Matlab function should i use to get the trendline? Im suspecting it would be in two degree of polynominal.

Image Analyst on 2 Mar 2020
Try this:
% X | Y | Z
% 11 | 13 | 14
% 8 | 15 | 15
% 6 | 17 | 16
% 3 | 19 | 14
% 1 | 22 | 14
% Make column vectors
x = [11,8,6,3,1]'
y = [13,15,17,19,22]'
z = [14,15,16,14,14]'
c = ones(size(z))
plot3(x, y, z, 'g.', 'MarkerSize', 30);
grid on;
% Z = aX^2 + bY^2 + cXY + dX + eY + f?
% Solve for Ax = B, where x are the coefficients, and B are the z values, and A is below
A = [x.^2, y.^2, x.*y, x, y, c]
coefficients = A \ z
% Get the estimated values
for row = 1 : size(x, 1)
zEstimate(row) = ...
coefficients(1) * x(row) ^2 + ...
coefficients(2) * y(row) ^2 + ...
coefficients(3) * x(row) .* y(row) + ...
coefficients(4) * x(row) + ...
coefficients(5) * y(row) + ...
coefficients(6);
fprintf('Actual z = %f, estimated z = %f.\n', z(row), zEstimate(row));
end
hold on;
plot3(x, y, zEstimate, 'r.', 'MarkerSize', 30);
If it's homework, you'll have to come up with your own code though since you probably can't turn in my code as your own. Anyway, you get:
coefficients =
0.0030033
0.032576
0.16415
-1.1685
-0.19148
0