How to let the axes in matlab have different lengths without changing axes limits - matlab

I'm trying to plot a 3D surface in Matlab and I want to "compress" the plot a little bit in the z dimension. Now the lengths of x, y and z axes are the same, and the plot looks like a cube. I'd like it to look flatter in the z dimension, without altering the axes limits.
Is there any easy way to achieve this?

Try fiddling with the DataAspectRatio and the PlotBoxAspectRatio properties of the axes, which may also be controlled by the pbaspect and daspect commands, correspondingly.
Example
%// Plot surface
[X, Y] = meshgrid(-10:.1:10, -10:.1:10);
Z = 100 - X .^ 2 - Y .^ 2;
surf(X, Y, Z, 'EdgeColor', 'None')
%// Flatten the z-axis a bit
pbaspect([1 1 .2])
daspect([1 1 50])
Original plot:
Flattened plot:

Related

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

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)

Bar3 plot with seperate x,y,height and width values

Solution posted below function to plot bar 3 with separate x, y values and separate width and height values
bar3(x,y,z,xWidth,yWidth)
We are currently working on a project that allow one to visualize the area under a 3d function, f(x,y). The purpose of this is to demonstrate how the bars cut a 3d surface. Indirectly to visualize the desired integral.
We wish to have the bars match up with the intervals of the surface grid.
Below is a rough demonstration of the idea.
bar3 only has input for the x-values bar3(x,z), where as surf has a input for both the x and y surf(x,y,z)
Unfortunately this is what we are getting. - this is because bar3 cant be in terms of x and y
CODE:
clc;
cla;
d=eval(get(handles.edtOuterUpperB,'string'));
c=eval(get(handles.edtOuterLowerB,'string'));
b=eval(get(handles.edtInnerUpperB,'string'));
a=eval(get(handles.edtInnerLowerB,'string'));
n=eval(get(handles.edtInnerInterval,'string'));
m=eval(get(handles.edtOuterInterval,'string'));
h=(b-a)/n;
k=(d-c)/m;
[x,y] = meshgrid(a:h:b, c:k:d);
f=eval(get(handles.edtFunc,'string'));
surf(x,y,f);
hold on
bar3(f,1);
If you look closely, you will see that the XData and YData are different from the mesh to the 3D bar plot. This is because your mesh uses "real" x and y values while the bar plot uses indexes for the x and y values.
To fix this, you will want to change one or the other. For your case, the easiest one to change is going to be the surface. You can actually just omit the x and y inputs and the indexed x and y values will be used instead by default when generating the surface.
surf(f);
From the documentation for surf:
surf(Z) creates a three-dimensional shaded surface from the z components in matrix Z, using x = 1:n and y = 1:m, where [m,n] = size(Z). The height, Z, is a single-valued function defined over a geometrically rectangular grid. Z specifies the color data, as well as surface height, so color is proportional to surface height.
Update
If you want to keep the non-indexed values on the x and y axes, you will want to convert the bar3 plot instead. Unfortunately, MATLAB provides a way to specify the x axis bot not the y axis. You can take one of two approaches.
Change the XData
You can get the XData property of the resulting bar objects and change them to the data you want.
x = a:h:b;
y = c:k:d;
%// Anonymous function to scale things for us
scaler = #(vals)x(1) + ((vals-1) * (x(end) - x(1)) / (numel(x) - 1));
%// Create the bar plot
bars = bar3(y, f);
%// Change the XData
xdata = get(bars, 'XData');
xdata = cellfun(scaler, xdata, 'uni', 0);
set(bars, {'XData'}, xdata);
set(gca, 'xtick', x)
%// Now plot the surface
surf(x,y,f);
And just to demonstrate what this does:
x = linspace(0.5, 1.5, 5);
y = linspace(2.5, 4.5, 4);
f = rand(4,5);
scaler = #(vals)x(1) + ((vals-1) * (x(end) - x(1)) / (numel(x) - 1));
bars = bar3(y, f);
set(bars, {'XData'}, cellfun(scaler, get(bars, 'XData'), 'uni', 0))
set(gca, 'xtick', x)
axis tight
Change the XTickLabels
Instead of changing the actual data, you could simply change the values that are displayed to be what you want them to be rather than the indexed values.
x = a:h:b;
y = c:k:d;
labels = arrayfun(#(x)sprintf('%.2f', x), x, 'uni', 0);
bar3(y, f);
set(gca, 'xtick', 1:numel(x), 'xticklabels', labels);
hold on
%// Make sure to use the INDEX values for the x variable
surf(1:numel(x), y, f);
We found a user contributed function scatterbar3, which does what we want, in a different way than what bar3 uses:
http://www.mathworks.com/matlabcentral/fileexchange/1420-scatterbar3
There was however a slight hiccup that we had to correct:
hold on
scatterbar3(x,y,f,h);
scatterbar3 does not have separate inputs for the width and height of the bars, thus large gaps occur when the intervals do not equal one another. Demonstrated below.
We thus edited the scatterbar3 function in order to take both the width and height of the bars as inputs:
Edited scatterbar3 function:
function scatterbar3(X,Y,Z,widthx,widthy)
[r,c]=size(Z);
for j=1:r,
for k=1:c,
if ~isnan(Z(j,k))
drawbar(X(j,k),Y(j,k),Z(j,k),widthx/2,widthy/2)
end
end
end
zlim=[min(Z(:)) max(Z(:))];
if zlim(1)>0,zlim(1)=0;end
if zlim(2)<0,zlim(2)=0;end
axis([min(X(:))-widthx max(X(:))+widthx min(Y(:))-widthy max(Y(:))+widthy zlim])
caxis([min(Z(:)) max(Z(:))])
function drawbar(x,y,z,widthx,widthy)
h(1)=patch([-widthx -widthx widthx widthx]+x,[-widthy widthy widthy -widthy]+y,[0 0 0 0],'b');
h(2)=patch(widthx.*[-1 -1 1 1]+x,widthy.*[-1 -1 -1 -1]+y,z.*[0 1 1 0],'b');
h(3)=patch(widthx.*[-1 -1 -1 -1]+x,widthy.*[-1 -1 1 1]+y,z.*[0 1 1 0],'b');
h(4)=patch([-widthx -widthx widthx widthx]+x,[-widthy widthy widthy -widthy]+y,[z z z z],'b');
h(5)=patch(widthx.*[-1 -1 1 1]+x,widthy.*[1 1 1 1]+y,z.*[0 1 1 0],'b');
h(6)=patch(widthx.*[1 1 1 1]+x,widthy.*[-1 -1 1 1]+y,z.*[0 1 1 0],'b');
set(h,'facecolor','flat','FaceVertexCData',z)
Finally the working solution in action:
hold on
scatterbar3(x,y,f,h,k);

Parametric curves on surfaces in MATLAB

Suppose we have
x=linspace(-1,1,25);
y=linspace(-1,1,25);
[X,Y]=meshgrid(x,y);
Z = X.^2 - Y.^2;
surf(Z)
How does MATLAB calculate the parametric curves (the black lines in the above figure) for obtaining the surface? Are there any explicit formulas to do that? If the parametrization is (u,v) then how to get MATLAB to spit out the
u=f(x,y,z)
v=g(x,y,z)
functions?
The black line on the surface is described by three vectors corresponding to x,y and z coordinates. For example, if you wish to extract the line corresponding to x=x(5)=-0.6667 you need to extract three vectors that are already contained in the meshgrid and Z-array - X(5,:),Y(5,:),Z(5,:):
x=linspace(-1,1,25);
y=linspace(-1,1,25);
[X,Y]=meshgrid(x,y);
Z = X.^2 - Y.^2;
hold off
surf(X,Y,Z)
hold on;
plot3(X(5,:),Y(5,:),Z(5,:),'r','LineWidth',5)
axis square
Similarly, if you want to extract the line at y=y(5)=-0.6667, then you need: X(:,5),Y(:,5),Z(:,5):
x=linspace(-1,1,25);
y=linspace(-1,1,25);
[X,Y]=meshgrid(x,y);
Z = X.^2 - Y.^2;
hold off
surf(X,Y,Z)
hold on;
plot3(X(:,5),Y(:,5),Z(:,5),'r','LineWidth',5)
axis square
Hope that helps

Graphing a hyperbola in Matlab

I'm trying to graph a solution obtained through the quadratic formula in Matlab. Since it's obtained by the quadratic formula, there are two parts: plus and minus. The graph should be a hyperbola. How can I place the upper part and the bottom part on the same graph?
There are different ways. Let's say you want to plot the solution of y^2 = x, that is y = ±sqrt(x):
You can plot the two parts with the same color using a plot once…
x = 0:0.1:10;
plot(x, sqrt(x), 'k', x, -sqrt(x), 'k')
…or twice:
x = 0:0.1:10;
plot(x, sqrt(x), 'k')
hold on
plot(x, -sqrt(x), 'k')
hold off
Or you can plot everything in one go like you might draw it with a pen:
x = [10:-0.1:0 0.1:0.1:10];
y = [-sqrt(10:-0.1:0) sqrt(0.1:0.1:10)];
plot(x, y)

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.