How to plot using surf gird in 2D using function value - matlab

if the function F is available it is easy to draw surf plot i.e.
x=1:0.1:4;
y=1:0.1:4;
[X,Y]=meshgrid(x,y);
Z=sin(X).^2+cos(Y).^2;
surf(X,Y,Z);
view(2) ;
in my case I calculated F function using least square:
for example I have x and y vectors
x = [0 9.8312 77.1256 117.9810 99.9979];
y = [0 2754.5 4043.3 5376.3 5050.4];
the linear function of these two vector is define by
F= [1149.73 , 37.63];
therefore the estimation is equal to
z= [ones(5,1) x']*F';
which is
z = [1149.73 1519.67 4051.96 5589.35 4912.65];
and if it is plotted
plot(x,y,'b.');
hold on;plot(x,y,'b-');
hold on; plot(x,z,'-r');
The linear z ( red line) is showing correctly. Now I want to plot it for all possible combination of x and y using grid and I need to have a mesh for all inputs
[X,Y] = meshgrid(x,y);
but how to make the Z matrix to show the intensity plot of function Z? The Z suppose to have high intensity close to z value and less value far from it. I should suppose to get something like this
Thanks
P.S: the F is calculated using pinv (least square).

You have to interpolate the scattered data to plot it on grid. Here is a simple example for your x, y and z vectors
xi=linspace(min(x),max(x),100)
yi=linspace(min(y),max(y),100)
[XI YI]=meshgrid(xi,yi);
ZI = griddata(x,y,z,XI,YI);
contourf(XI,YI,ZI)

Related

Plotting a function of two variables and pointwise minimization

How can I get a 3d-plot the following function in MATLAB?
f(x,y)=log(1+ (min(x,y))^2/(4*y));
I want to create a 3d-plot of f as a function of x and y. x and y are non-negative so they can range from 0 to any positive number like 10.
I tried to plot this with surf and meshgrid but it didn't work since I have a pointwise minimization.
first, create x and y with meshgrid :
[x,y] = meshgrid(0:0.5:10,0:0.5:10);
then compute function and plot :
k(:,:,1)=x;
k(:,:,2)=y;
% because x and y are 2d matrices in meshgrid, I defined 3d matrix k to compute minimum in third dimension:
z=log((1+ (min(k,[],3)).^2)./(4*y));
surf(x,y,z)

How to make a 2D contour plot with given data point in Octave/MATLAB?

I have a matrix whose three columns correspond to x, y and f values. I want to make a contour plot of f(x,y) in the x,y plane from these data with Octave/MATLAB.
Let's say, the matrix M is
x1 y1 f1
x2 y2 f2
x3 y3 f3
. . .
. . .
I found the function contourf requires f to be a matrix (whereas I have a vector with corresponding points).
How to generate this plot?
The x, y, and z variables that you pass to contourf are all matrices of the same size. For every point you need an x, y, and z value. You can use meshgrid to make matrices that have all the combinations of x and y values.
This example is from the doc for contourf. I added some comments to explain what is happening
% Create a vector of x values
x = linspace(-2*pi,2*pi);
% Create a vector of y values
y = linspace(0,4*pi);
% Make matrices with all combinations of x and y values for plotting
[X,Y] = meshgrid(x,y);
Z = sin(X)+cos(Y);
contourf(X,Y,Z)
This is the result of the above code

Plot a surface only for coordinates that satisfy a specific equation in MATLAB

I have two grid coordinates matrices, X and Y, created by calling [X, Y] = meshgrid(x, y), so their elements represent coordinates. How can I plot a surface on the xy-plane, using heights from matrix V, only for coordinates that satisfy a specific equation? For example, my plot extends up to radius a, but I dont want to plot any data to the set of points that satisfy the equation sqrt(x^2 + (y-c)^2) < b, where b, c (a>b) are given constants and x=X(i,j), y=Y(i,j). Is there an easy way to do this, other than creating the two grid coordinates matrices (up to radius a) and then manually removing elements from X, Y, V, using nested for loops? I have not found any way to limit the plotting area I am interested in by changing x, y.
Using Logical Indexing
Just in case you're still looking for any implementation details. Referencing the comment by #Ander Biguri. I have to add that it might be easier to use mesh parameters X and Y directly in the logical indexing. Here is a little playground script that might help future readers. Below Region_Array is a logical array that specifies where the condition in this case sqrt(X.^2 + (Y-c).^2) < b is true. When true Region_Array is indexed with the value "1" and elsewhere with "0". I've split this into two steps just in case the complementary region is quickly wanted. The images/plots below show the resulting surf() and masks/regions. MATLAB has some thorough documentation and examples overviewing logical indexing: Find Array Elements That Meet a Condition
Trivial Surface Plot:
Masks/Regions Not to be Plotted:
Playground Script:
%Random test axes%
x = linspace(0,100,50);
y = linspace(0,100,50);
[X,Y] = meshgrid(x,y);
%Trivial plot of ones%
V = ones(length(x),length(y));
%Constant parameters%
b = 20;
c = 10;
%Eliminating within the curved region%
figure(1)
Region_Array = sqrt(X.^2 + (Y-c).^2) < b;
V(Region_Array) = NaN;
subplot(1,2,1); surf(X,Y,V);
axis([0 100 0 100]);
title("Eliminating Within the Curved Region");
%Eliminating outside the curved region%
V = ones(length(x),length(y));
V(~Region_Array) = NaN;
subplot(1,2,2); surf(X,Y,V);
axis([0 100 0 100]);
title("Eliminating Outside the Curved Region");
figure(2)
subplot(1,2,1); imshow(~Region_Array,'InitialMagnification',200);
title("Region Array Mask/Map (Inside)")
subplot(1,2,2); imshow(Region_Array,'InitialMagnification',200);
title("Region Array Mask/Map (Outside)")
Ran using MATLAB R2019b

Matlab:Make a contour plot with 3 vectors

I have 3 vectors of data, X (position), Y (position) both of which are not regularly spaced, and Z(value of interest at each location). I tried contourf, which doesn't work because it needs a matrix for Z input.
You can also use griddata.
%Generate random data
x = rand(30,1);
y = rand(30,1);
z = rand(30,1);
%Create regular grid across data space
[X,Y] = meshgrid(linspace(min(x),max(x),n), linspace(min(y),max(y),n))
%create contour plot
contour(X,Y,griddata(x,y,z,X,Y))
%mark original data points
hold on;scatter(x,y,'o');hold off
For a contour plot you actually need either a matrix of z values, or a set (vector) of z-values evaluated on a grid. You cannot define contours using isolated Z values at (X,Y) points on the grid (i.e. what you claim you have).
You need to have the generating process (or function) provide values for a grid of (x,y) points.
If not, then you can create a surface from nonuniform data as #nate correctly pointed out, and then draw the contours on that surface.
Consider the following (random) example:
N = 64; % point set
x = -2 + 4*rand(N,1); % random x vector in[-2,2]
y = -2 + 4*rand(N,1); % random y vector in[-2,2]
% analytic function, or z-vector
z = x.*exp(-x.^2-y.^2);
% construct the interpolant function
F = TriScatteredInterp(x,y,z);
t = -2:.25:2; % sample uniformly the surface for matrices (qx, qy, qz)
[qx, qy] = meshgrid(t, t);
qz = F(qx, qy);
contour(qx, qy, qz); hold on;
plot(x,y,'bo'); hold off
The circles correspond to the original vector points with values (x,y,z) per point, the contours on the contours of the interpolant surface.

Texture mapping in MATLAB

I have points in 3D space and their corresponding 2D image points. How can I make a mesh out of the 3D points, then texture the triangle faces formed by the mesh?
Note that the function trisurf that you were originally trying to use returns a handle to a patch object. If you look at the 'FaceColor' property for patch objects, you can see that there is no 'texturemap' option. That option is only valid for the 'FaceColor' property of surface objects. You will therefore have to find a way to plot your triangular surface as a surface object instead of a patch object. Here are two ways to approach this:
If your data is in a uniform grid...
If the coordinates of your surface data represent a uniform grid such that z is a rectangular set of points that span from xmin to xmax in the x-axis and ymin to ymax in the y-axis, you can plot it using surf instead of trisurf:
Z = ... % N-by-M matrix of data
x = linspace(xmin, xmax, size(Z, 2)); % x-coordinates for columns of Z
y = linspace(ymin, ymax, size(Z, 1)); % y-coordinates for rows of Z
[X, Y] = meshgrid(x, y); % Create meshes for x and y
C = imread('image1.jpg'); % Load RGB image
h = surf(X, Y, Z, flipdim(C, 1), ... % Plot surface (flips rows of C, if needed)
'FaceColor', 'texturemap', ...
'EdgeColor', 'none');
axis equal
In order to illustrate the results of the above code, I initialized the data as Z = peaks;, used the built-in sample image 'peppers.png', and set the x and y values to span from 1 to 16. This resulted in the following texture-mapped surface:
If your data is non-uniformly spaced...
If your data are not regularly spaced, you can create a set of regularly-spaced X and Y coordinates (as I did above using meshgrid) and then use one of the functions griddata or TriScatteredInterp to interpolate a regular grid of Z values from your irregular set of z values. I discuss how to use these two functions in my answer to another SO question. Here's a refined version of the code you posted using TriScatteredInterp (Note: as of R2013a scatteredInterpolant is the recommended alternative):
x = ... % Scattered x data
y = ... % Scattered y data
z = ... % Scattered z data
xmin = min(x);
xmax = max(x);
ymin = min(y);
ymax = max(y);
F = TriScatteredInterp(x(:), y(:), z(:)); % Create interpolant
N = 50; % Number of y values in uniform grid
M = 50; % Number of x values in uniform grid
xu = linspace(xmin, xmax, M); % Uniform x-coordinates
yu = linspace(ymin, ymax, N); % Uniform y-coordinates
[X, Y] = meshgrid(xu, yu); % Create meshes for xu and yu
Z = F(X, Y); % Evaluate interpolant (N-by-M matrix)
C = imread('image1.jpg'); % Load RGB image
h = surf(X, Y, Z, flipdim(C, 1), ... % Plot surface
'FaceColor', 'texturemap', ...
'EdgeColor', 'none');
axis equal
In this case, you have to first choose the values of N and M for the size of your matrix Z. In order to illustrate the results of the above code, I initialized the data for x, y, and z as follows and used the built-in sample image 'peppers.png':
x = rand(1, 100)-0.5; % 100 random values in the range -0.5 to 0.5
y = rand(1, 100)-0.5; % 100 random values in the range -0.5 to 0.5
z = exp(-(x.^2+y.^2)./0.125); % Values from a 2-D Gaussian distribution
This resulted in the following texture-mapped surface:
Notice that there are jagged edges near the corners of the surface. These are places where there were too few points for TriScatteredInterp to adequately fit an interpolated surface. The Z values at these points are therefore nan, resulting in the surface point not being plotted.
If your texture is already in the proper geometry you can just use regular old texture mapping.
The link to the MathWorks documentation of texture mapping:
http://www.mathworks.com/access/helpdesk/help/techdoc/visualize/f0-18164.html#f0-9250
Re-EDIT: Updated the code a little:
Try this approach (I just got it to work).
a=imread('image.jpg');
b=double(a)/255;
[x,y,z]=peaks(30); %# This is a surface maker that you do have
%# The matrix [x,y,z] is the representation of the surface.
surf(x,y,z,b,'FaceColor','texturemap') %# Try this with any image and you
%# should see a pretty explanatory
%# result. (Just copy and paste) ;)
So [x,y,z] is the 'surface' or rather a matrix containing a number of points in the form (x,y,z) that are on the surface. Notice that the image is stretched to fit the surface.