# MATLAB Function Review

Some functions can be confusing in MATLAB are discussed in detail.

# surf

## Official Description

`surf`(X,Y,Z) uses Z for the color data and surface height. X and Y are vectors or matrices defining the x and y components of a surface. If X and Y are vectors, length(X) = n and length(Y) = m, where [m,n] = size(Z). In this case, the vertices of the surface faces are (X(j), Y(i), Z(i,j)) triples. To create X and Y matrices for arbitrary domains, use the meshgrid function.

## Explanation

From the description of `surf` function we can see, the most import thing to be noted is the dimension of vector X, vertor Y and matrix Z, where length(X) = the colum of Z and length(Y) = the row of Z. So, if we have following code:

```X = linspace(-5, 5, 40);
Y = linspace(-8, 8, 60);
Z = zeros(length(X), length(Y));
for i = 1:length(X)
for j = 1:length(Y)
Z(i, j) = X(i) .* exp(-X(i).^2 - Y(j).^2);
end
end
surf(X,Y,Z')```

We should note that transposeing Z is essential to match the equation, length(X) = the colum of Z and length(Y) = the row of Z. Even though length(X) = length(Y), based on the above code, transpose is also essential because of the property of `surf` function. If you do not transpose matrix Z, `surf` will work, but the axis of the figure will be flipped. Again, this is because of the property of `surf` function (Because `surf` calls `meshgrid` function, this phenomenon occurs.)

On the other hand, if we have following code:

```X = linspace(-5, 5, 40);
Y = linspace(-8, 8, 60);
[X, Y] = meshgrid(X, Y);
Z = X .* exp(-X.^2 - Y.^2);
figure
surf(X,Y,Z)```

We do not need to transpose Z, because we use `meshgrid` function before surf, and the output of `meshgird`, like X and Y, match the equation length(X) = the colum of Z and length(Y) = the row of Z. From the description, `meshgrid` function is used to create X and Y matrices for arbitrary domains.

# contour

## Official Description

contour(X,Y,Z), contour(X,Y,Z,n), and contour(X,Y,Z,v) draw contour plots of Z using X and Y to determine the x and y values.

If X and Y are vectors, then length(X) must equal size(Z,2) and length(Y) must equal size(Z,1). The vectors must be strictly increasing or strictly decreasing and cannot contain any repeated values.
If X and Y are matrices, then their sizes must equal the size of Z. Typically, you should set X and Y so that the columns are strictly increasing or strictly decreasing and the rows are uniform (or the rows are strictly increasing or strictly decreasing and the columns are uniform).

## Explanation

The usage of `contour` is the same as `surf` function, so refer to `surf` to find out the explanation.