I don't know hot to plot this nonlp's feasible reagion in matlab - matlab

I searched and watched how to plot the 3 dimensions of nonlp program's
but I still don't know how to plot these constraints.
x^2+y^2+z^2=1
x>=2*y
2*y>=3*z
x>=3*z
I programmed like this but it doesn't work and I think this is wrong program for upper constraints.
func1 = #(x,y,z) sqrt(1-x.^2-y.^2);
func2 = #(x,y,z) max(x-2*y,0);
func3 = #(x,z) max(x-3*z,0);
ezsurf(func1,[0 1 0 1]);
hold on;
ezsurf(func2,[0 1 0 1]);
hold on;
ezsurf(func3,[0 1 0 1]);
axis([0 1 0 1 0 1]);

A way of doing that is to work with volumetric data.
The idea is to create a 3D space, with a F value. F will be positive in one side of your main equation and negative in the other.
[X,Y,Z]=meshgrid(-2:0.05:2,-2:0.05:2,-2:0.05:2);
F=X.^2+Y.^2+Z.^2-1;
Then the conditions are applied to this F. If you want to see the object "cut"
then substitute the place where conditions are not met with nan. If you want to see a filled object, then substitute it with a positive number (it may need to be negative in another situation, so check this for other examples.
% Conditions
cond1=X>=2*Y;
cond2=2*Y>=3*Z;
cond3=X>=3*Z;
% If you want the boundaries to show
F1=F;
F1(~cond1)=1;
F1(~cond2)=1;
F1(~cond3)=1;
% If you want the boundaries not to show
F2=F;
F2(~cond1)=NaN;
F2(~cond2)=NaN;
F2(~cond3)=NaN;
Then the idea is to create an isosurface in the zero level (your original function). Here in this code I created 2 plots so you can see the differences between filling and not filling the boundaries. Also some fancy coding in order to get nice figures. However the isosurface and patch parts are relevant to obtain the surface and plot it.
subplot(121)
iso1=isosurface(X,Y,Z,F1,0);
p=patch(iso1);
isonormals(X,Y,Z,F1,p);
set(p,'FaceColor','red','EdgeColor','none');
daspect([1 1 1])
axis equal
camlight
lighting gouraud
subplot(122)
iso2=isosurface(X,Y,Z,F2,0);
p=patch(iso2);
isonormals(X,Y,Z,F2,p);
set(p,'FaceColor','red','EdgeColor','none');
axis equal
daspect([1 1 1])
camlight headlight
lighting gouraud
Result:
Additionally, You can calculate the isosurface of the initial boundary F and plot it with a low alpha value, so you can better understand what piece of the domain you are actually selecting.

Related

MATLAB focus plot and apply correct tick labels

I'd much rather be asking you about Bayesian analysis over this, but unfortunately, I am terrible with MATLAB plots (not due to a lack of effort though).
I have a plot attached. It contains 1739 days of data. I need to do the following three things:
Focus in on the plot so that the y axis limits are -1 and 1 (right now they are -4 and 14). I'm uninterested in any values beyond these limits.
Re-label the y axis from -1 to 1 in .10 increments.
Re-label the x axis so that it starts with 1, ends with 1739, and has enough points in between that it is still readable.
I've studied gca, datetick, ax=gca, etc. but I cannot accomplish any of these tasks without messing up the plot.
I am gracious for any assistance provided.
Changing the axis limits is very simple,
axis([1 1739 -1 1]) %// [xMin xMax yMin yMax]
And for the tick marks, do
set(gca,'XTick',-1:.1:1,'YTick',1:79:1739) %// 2*79 might be better than 79
after you create the plot. You can (should?) replace gca with the handle to the plot (do h=plot(... when you make the plot, then set(h,'XTick',...).
You should also go through Matlab Plotting Basics which goes through all this kind of stuff in good detail.

Changing perspective of Matlab plots

Say I have a matrix hey 15x15. I want to plot the value of the matrix as a 2D plot for better visualization. But Matlab plots with the convention that origin is in bottom-left corner and positive x is along the left and positive y is along the up direction from origin.
but i want to make my plots such that origin is in top-left corner, +ve x is left and +ve y is down.
So i just used a slight trick.
figure
axis([0 15 -15 0]);
daspect([1,1,1])
hold on
rectangle('Position',[3,-6,2,3],...
'EdgeColor','black',...
'LineWidth',2,...
'FaceColor','cyan')
for i=1:nrows
for j=1:ncolumns
if char(hey(i,j))=='^'
text(j,-i,'^');
elseif char(hey(i,j))=='>'
text(j,-i,'>');
elseif char(hey(i,j))=='v'
text(j,-i,'v');
elseif char(hey(i,j))=='<'
text(j,-i,'<');
end
if obstacle(i,j)==1
text(j,-i,'X');
end
end
end
text(goalY,-goalX,'T');
I made the transformation (x,y)-->(y,-x). But the downside is that the axes are then numbered along y as -1 to -15. However if reader was following above, i only wanted to plot the matrix values and in matrix the y runs +ve downwards from 1 to 15 for my case.
So i want the plot to show +1 thru +15 along y with origin at top-left and x graduated as it is but the values +1 to +15 written at the top of the plot rather than below.
How to do this? In the extreme case, i am alos willing to transfer the matrix hey to another software that can do the nice plot as i want. If any of the two alternatives is possible, please give concrete steps to do it.
EDIT:
After using the helpful methods below, i still have to use a trick like plot (j,i) instead of the innocent plot(i,j). This is because for matrix (i,j) is mapped to graph plot (x,y) as x=j, y=i. Is there a similar workaround? a matrix element is (row #, column #). But in 2D matlab graph, we will denote it's position as (column #, row #). I was just guessing if there was some matlab in-built function to take care of this. like i will give it (row #, column #) but matlab will plot (column #, row #). Is there such a function?
I think axis ij does what you want:
axis ij places the coordinate system origin in the upper left corner. The i-axis is vertical, with values increasing from top to bottom. The j-axis is horizontal with values increasing from left to right.
To locate the x axis on top, change the 'XAxisLocation' of the axes to 'top' (default is 'bottom').
Example:
x = 1:10;
y = x.^2;
plot(x,y)
axis ij
set(gca,'XAxisLocation','top')
Original plot (lines 1-3 of above code):
After axis ij (line 4):
After set(gca,'XAxisLocation','top') (line 5):
If I followed correctly you are looking for the axes XAxisLocation and YDir properties. You can set them to top and reverse respectively to get the output you want. You can also set the XTick property to 1:15 to show every value from 1 to 15.
Example:
clear
clc
%// Create dummy data
[x,y] = meshgrid(1:15,1:15);
u = cos(x).*y;
v = sin(x).*y;
figure
quiver(x,y,u,v)
set(gca,'XAxisLocation','top','XTick',1:15,'YDir','reverse')
hold on
%// I changed the coordinated of the rectangle to fit with the change in
%y-axis.
rectangle('Position',[3,3,2,3],...
'EdgeColor','black',...
'LineWidth',2,...
'FaceColor','cyan')
axis([0 15 0 15])
Which gives the following:

Matlab plotting through origin regardless of only negative or only positive data

this one should be really easy to answer, yet I am surprised it is nowhere described:
I have variable data, and often when I simply plot, I get a close-up on the y-axis (x-axis is time and starts always with a zero). So I get y-values from 16-17, but the zero is nowhere to be seen. I know you can give matlab an YLim value, yet sometimes because my data is variable, I get a range from -50-100 in y. If i had specified before that YLim is [0 20] I wouldnt see it at all, which is not what I want. I just always want to have the origin plotted with my data, how do I do that (without a rigid interval like [-1000 1000], since sometimes I have y values from -0,01-0,001 and wouldnt see it)? Please help if you have an idea!
Thanks!
UPDATE 1: perfectly solved!
Follow-up question:
There is one thing I didnt mention: I need to do this for all my 18 subplots. How can I avoid hardcoding it?
One way to do this is automatically is to use:
ylim([min([y 0]) max([y,0])])
this way, it will start or stop at 0 if 0 is not already in the range of y
or better, if you want to keep the rounded values matlab provides (eg plot on [0,6] and not on [0,5.872]), first plot your data with plot(x,y), then change the ylim values to 0 if needed:
ylim([min([ylim 0]) max([ylim 0])])
It's easy to manually modify axis size:
x = 1:10; %/ example x
y = 5 + rand(1,10); %// example y. Values between 5 and 6
plot(x,y) %// do the plot normally
ax = axis; %// get axis size
ax(3) = min(ax(3),0); %// if the y-axis lower limit is positive, make it 0
axis(ax) %// apply new axis size values
This also seems to work: just use
plot([x NaN],[y 0])
That is, include a point with x value set to NaN and y value set to 0. The point doesn't get plotted (because of the NaN value) but it forces the y axis to strech out to 0.

Plotting shaded deviation of a line in Matlab

I would like to plot a line, and in grey-shaded X% deviation of a signal, in MATLAB. Then, I'd plot another signal and see (visually) how much of the second signal is outside the gret-shaded area.
The task I'd like to get help done is the shaded area: similar to the image attached below.
I am aware of similar solutions with errorbar, but I think this is a much clearer plot to visualize.
If for example I had:
x = 0:0.1:10;
y = 1 + sin(x);
What would the 5% grey-shaded plot of y look like? (that area?)
See this answer for an example: MATLAB fill area between lines
Do you have the error of y at each sample in x? Let's assume you have and the upper bound is in variable yu and the lower bound in variable yl. Then you could plot it using:
x = 0:0.1:10;
y = 1 + sin(x);
% I create some yu and yl here, for the example
yu = y+.1;
yl = y-.1;
fill([x fliplr(x)], [yu fliplr(yl)], [.9 .9 .9], 'linestyle', 'none')
hold all
plot(x,y)
fill(X,Y,ColorSpec,...) plots a polygon with edges specified in the first two parameters. You have to fliplr (flip left-right) the arrays, so that it correctly draws the shape of the area to be filled 'in a circle' around it. The [.9 .9 .9] is the colour specification, in this case a light grey. I removed the edge by setting no line, to make it even more similar to your desired plot. One detail: plot the filled area before plotting y, because the last plotted object goes on top of the others.

How to avoid curved corners in rectangular patch element in matlab figure?

When I generate a set of rectangular patches in a matlab figure, some of the rectangle edges are rendered curved or clipped rather than sharp, which is unwanted. This depends on the scale, zooming into the image tends to eliminate the effect. I thought this might have to do with an aliasing/compression effect. Curiously, using rectangle the problem seems to go away.
Here is an example of the problem at intermediate magnification (other problems such as dashed borders which shouldn't be there are also evident):
The code is from an answer to another question:
H=Hadamard(48); %# now to row-double the matrix
A=(1+H)/2;
B=(1-H)/2;
C=[A; B]; %# the code below randomly permutes elements within the rows of the matrix
[nRows,nCols] = size(C);
[junk,idx] = sort(rand(nRows,nCols),2); %# convert column indices into linear indices
idx = (idx-1)*nRows + ndgrid(1:nRows,1:nCols); %# rearrange whatever matrix
E = C;
E(:) = E(idx);
[X Y] = find(logical(E));
xl = length(X);
yl = length(Y);
figure, hold on
for ii=1:xl
patch(X(ii) + [0 0 1 1],Y(ii) + [0.15 0.9 0.9 0.1],[1 1 1],'Edgecolor',[1 1 1])
end
axis([0 max(X)+1 0 max(Y)+1])
axis('square')
set(gca,'color',[0 0 0])
set(gca,'XTickLabel',[],'YTickLabel',[],'XTick',[],'YTick',[])
My questions are:
(1) Is it possible (and how) to get rid of the curved corners and other glitches of patch objects seen in the example shown, at low to intermediate degrees of magnification used to display the entire figure on screen.
(2) Most important is to be able to generate an image file (jpg, png, pdf...) which lacks the curved corners. All formats I looked into appear to conserve the unwanted effect. Answering 2 makes answering (1) essentially unimportant, and answering (1) presumably solves (2).
Edit
Since the problem goes away when rectangle is used, this appears to be a problem with the matlab rendering engine? Note: the example was generated with R14 but the OP of the question linked to had similar problems (matlab version unknown).
I went through the various lighting and edge representation options available for patch objects but no improvement was observed.
The question is a likely repeat, for instance a similar questions was asked here.
The answer appears to be to avoid explicit use of patch when drawing rectangles. Use either fill or just rectangle instead. The following ways of generating the figure provide nearly equivalent results, as far as I could tell:
load had.mat % <-- load the data containing the matrix of interest in array E
[X Y] = find(logical(E));
xl = length(X);
yl = length(Y);
figure, hold on
for ii=1:xl
rectangle('Position',[X(ii) Y(ii)+.2 1 0.8],'facecolor',[1 1 1],'edgecolor',[1 1 1])
% fill([X(ii) X(ii) X(ii)+1 X(ii)+1], [Y(ii)+0.2 Y(ii)+0.8 Y(ii)+0.8 Y(ii)+0.2],[1 1 1],'edgecolor',[1 1 1],'marker','.','markersize',1)
end
set(gca,'color',[0 0 0])
set(gca,'XTickLabel',[],'YTickLabel',[],'XTick',[],'YTick',[])
set(gcf,'Renderer','zbuffer')