Satisfying an inequality in an Octave 3D plot - octave

Suppose I generate a plot in the following way:
x=linspace(-2,2,50);
y=linspace(-2,2,50);
[xx,yy]=meshgrid(x,y);
mesh(xx,yy,4-(xx.^2+yy.^2))
Is there anyway to impose an inequality such that I only plot values where x < y?

One possible hack:
x = y = linspace(-2, 2, 50);
[xx, yy] = meshgrid(x, y);
cond = xx < yy;
xx = xx .* cond;
yy = yy .* cond;
mesh(xx, yy, 4-(xx.^2+yy.^2));
Strictly speaking, this will move all coordinate pairs (x,y) that do not meet the criterion x < y from their current location to the origin of the plot:

This is fairly similar to another answer already provided, but might help with the "strange aberration" you mention that answer caused in your data. Basically create a mask that is 1 where xx < yy, and 0 otherwise:
mask = xx < yy;
Then apply this mask to your xx and yy meshes:
xx_mask = xx.*mask;
yy_mask = yy.*mask;
And only then do you plot your results:
mesh(xx_mask, yy_mask, 4-(xx_mask.^2 + yy_mask.^2));
Basically the only difference is that this way you are setting the unwanted values in your xx and yy matrices to zero before you square them and plot them.
Note, this was tested with MATLAB instead of Octave, but they should give similar results.

Solutions above are only good if the point (0,0) is part of your chart. Otherwise it adds the point to the chart and then tries to plot, creating strange effect, like below.
[![x=linspace(1,3,50);
y=linspace(1,3,50);
\[xx,yy\]=meshgrid(x,y);
mask = xx < yy;
xx_mask = xx.*mask;
yy_mask = yy.*mask;
mesh(xx_mask, yy_mask, 4-(xx_mask.^2 + yy_mask.^2));][1]][1]
What can be alternatively be done is to leave x and y axes values as is and only convert z axis values to NA inthe range not satisfying the condition.
x=linspace(1,3,50);
y=linspace(1,3,50);
[xx,yy]=meshgrid(x,y);
mask = xx < yy;
function result = applyCondition(cond)
result = ifelse(cond, 0, NA);
endfunction
zz = 4-(xx.^2 + yy.^2);
mesh(xx, yy, zz + arrayfun(#applyCondition, mask));
This solution works in all cases, regardless of (0,0) being part of you chart of not.

Related

How to plot a 2d Function in MATLAB

I am trying to plot a simple equation in MATLAB.
The equation is
z = x^2 - y^2, for -3 <= x <= 3, -3 <= y <= 3.
The current code that I have is
x = -3:3;
y = -3:3;
z = (x.^2) - (y.^2);
plot(z)
The result is
Please help me in this case because I am not sure if the code and graph is correct. Thank you very much.
This is not a piecewise function. A Piecewise Function is a function defined by multiple sub-functions, where each sub-function applies to a different interval in the domain. There is only one function here that takes two arrays of the same length. The calculations yield a vector of zeros, due to the input arrays. If you change either one of the vectors, that is "x" or "y", you will see a nonzero plot. Your code works as expected.
There is a lot going wrong here: Let's start at the beginning:
x = -3:3;
y = -3:3;
If we evaluate these they both will return an vector of integers:
x =
-3 -2 -1 0 1 2 3
This means that the grid on which the function is evaluated is going to be very coarse. To alleviate this you can define a step size, e.g. x = 3:0.1:3 or use linspace, in which case you set the number of samples, so e.g. x = linspace(-3, 3, 500). Now consider the next line:
z = (x.^2) - (y.^2);
If we evaluate this we get
z =
0 0 0 0 0 0 0
and you plot this vector with the 2d-plotting function
plot(z)
which perfectly explains why you get a straight line. This is because the automatic broadcasting of the arithmetic operators like minuse (-) just subtracts values entry-wise. You however want to evaluate z for each possible pair of values of x and y. To do this and to get a nice plot later you should use meshgrid, and use a plotting function like mesh to plot it. So I'd recommend using
[X,Y] = meshgrid(x,y);
to create the grid and then evaluate the function on the grid as follows
Z = X.^2 - Y.^2;
and finally plot your function with
mesh(X,Y,Z);

Plotting decision boundary line in Octave

I have been working on a machine learning course and currently on Classification. I implemented the classification algorithm and obtained the parameters as well as the cost. The assignment already has a function for plotting the decision boundary and it worked but I was trying to read their code and cannot understand these lines.
plot_x = [min(X(:,2))-2, max(X(:,2))+2];
% Calculate the decision boundary line
plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));
Anyone explain?
I'm also taking the same course as you. I guess what the code does is to generate two points on the decision line.
As you know you have the function:
theta0 + theta1 * x1 + theta2 * x2 = 0
Which it can be rewritten as:
c + mx + ky = 0
where x and y are the axis corresponding to x1 and x2, c is theta(0) or the y-intercept, m is the slope or theta(1), and k is theta(2).
This equation (c + mx + ky = 0) corresponds to the decision boundary, so the code is finding two values for x (or x1) which cover the whole dataset (-2 and +2 in plot_x min and max functions) and then uses the equation to find the corresponding y (or x2) values. Finally, a decision boundary can be plotted -- plot(plot_x, plot_y).
In other words, what it does is to use the the equation to generate two points to plot the line on graph, the reason of doing this is that Octave cannot plot the line given an equation to it.
Hope this can help you, sorry for any mistake in grammar or unclear explanation ^.^
Rearranging equations helped me, so adding those here:
plot_y = -1/theta2 (theta1*plot_x + theta0)
note that index in Octave starts at 1, not at 0, so theta(3) = theta2, theta(2) = theta1 and theta(1) = theta0.
This plot_y equation is equivalent to:
c + mx + ky = 0 <=>
-ky = mx + c <=>
y = -1/k (mx + c)

Octave - gradients of a circle function do not plot correctly

Question
Trying to follow Gradients, Gradient Plots and Tangent Planes.
The gradient vectors of (X^2 + Y^2) do not show up correctly in Octave 4.2.0 on Windows. With the code, expected the gradients of a circle diverge from center outwards. However the actual is diagonal.
Please assist to understand what is wrong.
syms x y
f1 = x^2 + y^2;
gradf1 = jacobian(f1,[x,y]);
f1fun = function_handle(f1);
f1xfun = function_handle(gradf1(1));
f1yfun = function_handle(gradf1(2));
[xx, yy] = meshgrid(-1:.1:1,-1:.1:1);
hold on
contour(xx, yy, f1fun(xx, yy), 10)
quiver(xx, yy, f1xfun(xx, yy), f1yfun(xx, yy), 0.5)
axis equal tight
hold off
Expected
Actual
When you perform:
f1xfun = function_handle(gradf1(1));
f1yfun = function_handle(gradf1(2));
The output is:
f1xfun =
#(x) 2 * x % note: single-argument function
f1yfun =
#(y) 2 * y % note: single-argument function
that is AS OPPOSED TO
f1xfun =
#(x,y) 2 * x % two-argument function
f1yfun =
#(x,y) 2 * y % two-argument function
which is what you seem to think was happening. (i.e. the resulting functions actually only take a single input, not both x and y).
Therefore later on when you call f1yfun with two inputs, the second input (i.e. y) is simply silently discarded, and you are essentially calculating 2*x in both axes, hence the diagonal arrows.
tl;dr Your call to quiver should be:
quiver(xx, yy, f1xfun(xx), f1yfun(yy), 0.5);
I think you have a bug in your code and the call to quiver should be
quiver(xx, yy, f1xfun(xx), f1yfun(yy), 0.5)
which then gives (with colormap("jet"))

Sympy: Substitution with functions

I have a function f:
f = Function('f')(x,y).
The output of my program is a large polynomial with terms XYf, Xf, Yf for variables X and Y. I would like to define the substitution such that
X f(x,y) = f(x+1,y)
Y f(x,y) = f(x,y+1)
Similarly, XY f(x,y) = f(x+1,y+1).
I have used the following code to define the operation of X and Y.
poly = poly.subs(X*f, f.subs(x,x+1))
poly = poly.subs(Y*f, f.subs(y,y+1))
Though this works with terms of Xf and Yf, it does not work with terms of XYf. XYf gives the output as Yf(x+1,y) instead of f(x+1,y+1).
How do I force Y to act on the "new" f?
XYf gives Yf(x+1, y) because it matches Xf and that's the first substitution you do. To replace all three in the way that you want, you should do them in an order such that you don't match later instances, like
poly = poly.subs(X*Y*f, f.subs(x,x+1).subs(y, y + 1))
poly = poly.subs(X*f, f.subs(x,x+1))
poly = poly.subs(Y*f, f.subs(y,y+1))
That way, you replace all X*Y*f(x, y) first, so when you replace X*f(x, y) and Y*f(x, y) it won't replace X*Y*f(x, y) (because they will already be replaced).
As a side note, in terms of code clarity, it's going to be simpler if you just define
f = Function('f')
and then explicitly write f(x, y), f(x + 1, y), and so on (rather than letting f = f(x, y) and using subs to create f(x + 1, y) and so on).

Correct solution for this tensor

I'm implementing the system in this paper and I've come a little unstuck correctly implementing the radial tensor field.
All tensors in this system are of the form given on page 3, section 4
R [ cos(2t), sin(2t); sin(2t), -cos(2t) ]
The radial tensor field is defined as:
R [ yy - xx, -2xy; -2xy, -(yy-xx) ]
In my system I'm only storing R and Theta, since I can calculate the tensor based off just that information. This means I need to calculate R and Theta for the radial tensor. Unfortunately, my attempts at this have failed. Although it looks correct, my solution fails in the top left and bottom right quadrants.
Addendum: Following on from discussion in the comments about the image of the system not working, I'll put some hard numbers here too.
The entire tensor field is 800x480, the center point is at { 400, 240 }, and we're using the standard graphics coordinate system with a negative y axis (ie. origin in the top left).
At { 400, 240 }, the tensor is R = 0, T = 0
At { 200, 120 }, the tensor is R = 2.95936E+9, T = 2.111216
At { 600, 120 }, the tensor is R = 2.95936E+9, T = 1.03037679
I can easily sample any more points which you think may help.
The code I'm using to calculate values is:
float x = i - center.X;
float xSqr = x * x;
float y = j - center.Y;
float ySqr = y * y;
float r = (float)Math.Pow(xSqr + ySqr, 2);
float theta = (float)Math.Atan2((-2 * x * y), (ySqr - xSqr)) / 2;
if (theta < 0)
theta += MathHelper.Pi;
Evidently you are comparing formulas (1) and (2) of the paper. Note the scalar multiple l = || (u_x,u_y) || in formula (1), and identify that with R early in the section. This factor is implicit in formula (2), so to make them match we have to factor R out.
Formula (2) works with an offset from the "center" (x0,y0) of the radial map:
x = xp - x0
y = yp - y0
to form the given 2x2 matrix:
y^2 - x^2 -2xy
-2xy -(y^2 - x^2)
We need to factor out a scalar R from this matrix to get a traceless orthogonal 2x2 matrix as in formula (1):
cos(2t) sin(2t)
sin(2t) -cos(2t)
Since cos^2(2t) + sin^2(2t) = 1 the factor R can be identified as:
R = (y^2 - x^2)^2 + (-2xy)^2 = (x^2 + y^2)^2
leaving a traceless orthogonal 2x2 matrix:
C S
S -C
from which the angle 'tan(2t) = S/C` can be extracted by an inverse trig function.
Well, almost. As belisarius warns, we need to check that angle t is in the correct quadrant. The authors of the paper write at the beginning of Sec. 4 that their "t" (which refers to the tensor) depends on R >= 0 and theta (your t) lying in [0,2pi) according to the formula R [ cos(2t), sin(2t); sin(2t) -cos(2t) ].
Since sine and cosine have period 2pi, t (theta) is only uniquely determined up to an interval of length pi. I suspect the authors meant to write either that 2t lies in [0,2pi) or more simply that t lies in [0,pi). belisarius suggestion to use "the atan2 equivalent" will avoid any division by zero. We may (if the function returns a negative value) need to add pi so that t >= 0. This amounts to adding 2pi to 2t, so it doesn't affect the signs of the entries in the traceless orthogonal matrix (since 'R >= 0` the pattern of signs should agree in formulas (1) and (2) ).