3
votes

How to plot a square surface in Matlab?

More exactly I want to plot a square square with value 0.5 surface which is located at X:-1 to X=1 and Y:2.5 to 3.5.

I tried the following

[X,Y] = meshgrid(-3.5:.5:3.5);
Z = zeros(15);
Z(end-2:end,5:9) = 0.5;
surf(X,Y,Z);

This doesn't result in a perpendicular edge. How to archive that?

3

3 Answers

4
votes

This is what the patch function is for.

Matlab documentation

so for your case:

X = [ -1  -1   1   1];
Y = [3.5 2.5 2.5 3.5];
Z = [0.5 0.5 0.5 0.5];

patch(X,Y,Z,'red')
view(45,45)

example

2
votes

You need to provide multiple Z-values together with the same X, Y values. A small example:

>> [X, Y]= meshgrid([1,2,2,3,4], 1:2)
X =
     1     2     2     3     4
     1     2     2     3     4
Y =
     1     1     1     1     1
     2     2     2     2     2
>> Z = [0,0,1,1,0;0,0,1,1,0]
Z =
     0     0     1     1     0
     0     0     1     1     0
>> surf(X, Y, Z)

Yields this:

Step at X=2, slope at X=3..4

This should be the same in 2D, you just need to wrap you head around which X and Y values to duplicate and adjust the Z-Matrix accordingly.

0
votes

I ended up with

figure;
hold on;

X = [ -2  -2   2 2];
Y = [2 4 4 2];
Z = [0 0 0 0];
patch(X,Y,Z,'blue');

X = [ -1  -1   1   1];
Y = [3.5 2.5 2.5 3.5];
Z = [0.5 0.5 0.5 0.5];
h = patch(X,Y,Z,'red');

X = [ -1 -1 1 1];
Y = [2.5 2.5 2.5 2.5];
Z = [0 0.5 0.5 0];
patch(X,Y,Z,'red');

X = [1, 1, 1, 1];
Y = [2.5 2.5 3.5 3.5];
Z = [0 0.5 0.5 0];
patch(X,Y,Z,'red');

view(45,30)
legend(h, 'F(u,v)')
xlabel('u')
ylabel('v')
zlabel('F(u,v)')