Quadratic surface plotting in Octave - plot

I've been assigned a project that requires me to plot some quadratic surfaces. I tried to be diligent and download some software so that my graphs look better than those done with other free online resources. I decided to try Octave and see if I can make it work but I've ran into a problem. When trying to plot:
I've checked some tutorials but so far I haven't been able to pinpoint my error. This is the code I was using:
clear;
x = [-3:1:3];
y = x;
[xx,yy] = meshgrid(x,y);
zz=sqrt(-9*xx.^2+9*yy.^2);
figure
mesh(xx,yy,zz);
Any suggestions are appreciated.

The error thrown to the command window for your script is:
error: mesh: X, Y, Z, C arguments must be real
error: called from
mesh at line 61 column 5
blah at line 15 column 1
Since you x and y are real, the imaginaries are coming from a square-root of a number less than 0. Looking at your equation, this will happen for any (x, y) pair where x is greater than y.
The easiest fix is to set all complex numbers (values of zz with a non-zero imaginary part) to 0 (which will plot the value) or NaN (which will not plot the value. Consider this script (yours plus filtering):
clear;
x = -3:0.1:3;
y = x;
[xx,yy] = meshgrid(x,y);
zz=sqrt(-9*xx.^2+9*yy.^2);
figure
% Set all zz with nonzero imaginary part to NaN
zz(imag(zz)~=0) = NaN;
% % Set all zz with nonzero imaginary part to 0
% zz(imag(zz)~=0) = 0;
mesh(xx,yy,zz);

I would prefer this:
x = -3:0.1:3;
y = x;
[xx,yy] = meshgrid(x,y);
zz=sqrt(-9*xx.^2+9*yy.^2); % zz will have both + and -
figure
% zz = abs(zz) ;
mesh(xx,yy,abs(zz));
hold on
mesh(xx,yy,-abs(zz));

Related

Plot of function, DomainError. Exponentiation yielding a complex result requires a complex argument

Background
I read here that newton method fails on function x^(1/3) when it's inital step is 1. I am tring to test it in julia jupyter notebook.
I want to print a plot of function x^(1/3)
then I want to run code
f = x->x^(1/3)
D(f) = x->ForwardDiff.derivative(f, float(x))
x = find_zero((f, D(f)),1, Roots.Newton(),verbose=true)
Problem:
How to print chart of function x^(1/3) in range eg.(-1,1)
I tried
f = x->x^(1/3)
plot(f,-1,1)
I got
I changed code to
f = x->(x+0im)^(1/3)
plot(f,-1,1)
I got
I want my plot to look like a plot of x^(1/3) in google
However I can not print more than a half of it
That's because x^(1/3) does not always return a real (as in numbers) result or the real cube root of x. For negative numbers, the exponentiation function with some powers like (1/3 or 1.254 and I suppose all non-integers) will return a Complex. For type-stability requirements in Julia, this operation applied to a negative Real gives a DomainError. This behavior is also noted in Frequently Asked Questions section of Julia manual.
julia> (-1)^(1/3)
ERROR: DomainError with -1.0:
Exponentiation yielding a complex result requires a complex argument.
Replace x^y with (x+0im)^y, Complex(x)^y, or similar.
julia> Complex(-1)^(1/3)
0.5 + 0.8660254037844386im
Note that The behavior of returning a complex number for exponentiation of negative values is not really different than, say, MATLAB's behavior
>>> (-1)^(1/3)
ans =
0.5000 + 0.8660i
What you want, however, is to plot the real cube root.
You can go with
plot(x -> x < 0 ? -(-x)^(1//3) : x^(1//3), -1, 1)
to enforce real cube root or use the built-in cbrt function for that instead.
plot(cbrt, -1, 1)
It also has an alias ∛.
plot(∛, -1, 1)
F(x) is an odd function, you just use [0 1] as input variable.
The plot on [-1 0] is deducted as follow
The code is below
import numpy as np
import matplotlib.pyplot as plt
# Function f
f = lambda x: x**(1/3)
fig, ax = plt.subplots()
x1 = np.linspace(0, 1, num = 100)
x2 = np.linspace(-1, 0, num = 100)
ax.plot(x1, f(x1))
ax.plot(x2, -f(x1[::-1]))
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
plt.show()
Plot
That Google plot makes no sense to me. For x > 0 it's ok, but for negative values of x the correct result is complex, and the Google plot appears to be showing the negative of the absolute value, which is strange.
Below you can see the output from Matlab, which is less fussy about types than Julia. As you can see it does not agree with your plot.
From the plot you can see that positive x values give a real-valued answer, while negative x give a complex-valued answer. The reason Julia errors for negative inputs, is that they are very concerned with type stability. Having the output type of a function depend on the input value would cause a type instability, which harms performance. This is less of a concern for Matlab or Python, etc.
If you want a plot similar the above in Julia, you can define your function like this:
f = x -> sign(x) * abs(complex(x)^(1/3))
Edit: Actually, a better and faster version is
f = x -> sign(x) * abs(x)^(1/3)
Yeah, it looks awkward, but that's because you want a really strange plot, which imho makes no sense for the function x^(1/3).

How to convert this equation to Octave code and plot

I have an equation that I created on Desmos website
I used the code below to try and recreate it in Octave. But when I plot it, it comes out different. How can I fix the code in Octave (without changing the main equation, if possible) so it looks like the Desmos image?
x = linspace(0,1,20);
y = linspace(0,1,20);
S=[13.2];
T=1.12;
for zz=1:1:length(S)
eq1=exp(S(1,zz)*T*log(x))+exp(S(1,zz)*T*log(y));
hold on
plot(x,eq1)
zz
end
PS: I'm using Octave 4.2.2
S = 13.2;
T = 1.12;
f = #(x)exp(log(1-exp(S*T*log(x)))./(S*T));
fplot(f, [0, 1])
Desmos.com does not plot (x,eq1) but (x,y) with the constraint that x, y satisfy the given equation. So, you solve for y for each value of x, and plot the pairs (x,y).
Since log(x), log(y) exist, x and y are >0 (otherwise you would have to plot for x<0 as well).
clear; clc;
x = linspace(0,1,150);
S = 13.2;
T = 1.12;
y = zeros(size(x));
for i = 1:length(x)
y(i) = (1-exp(S*T*log(x(i))))^(1/S/T);
end
plot(x,y)
Notes:
1) I assume by log(x) you mean ln(x) (logarithm using base e).
2) I used a more dense discretization with 150 points so that the plotted curve appears smoother.
3) Mathematically, linspace(0,1,150) should not work, as log(x=0) is not defined. However for Matlab log(0) = -inf which means that exp(-inf) = 0. That's why no runtime error is thrown.
4) By the way, the provided equation can be simplified to x^(ST) + y^(ST) = 1, with the constraints that x, y > 0.

How to find the intecept x and y coordinates from 4 data points in Excel?

I have two points which form one line: (1,4) and (3,6), and another two which form another line: (2,1) and (4,2). These lines are continuous and I can find their intersection points by finding the equation for each line, and then equating them to find the x value at the intersection point, and then the y value.
i.e. for the first line, the equation is y = x + 3, and the second is y = 0.5x. At the intersection the y values are the same so x + 3 = 0.5x. So x = -6. Subbing this back into either of the equations gives a y value of -3.
From those steps, I now know that the intersection point is (-6,-3). The problem is I need to do the same steps in Excel, preferably as one formula. Can anyone give me some advice on how I would start this?
Its long but here it is:
Define x1,y1 and x2,y2 for the 1st line and x3,y3 and x4,y4 for the second.
x = (x2y1-x1y2)(x4-x3)-(x4y3-x3y4)(x2-x1) / [ (x2-x1)(y4-y3) - (x4-x3)(y2-y1) ]
y = (x2y1-x1y2)(y4-y3)-(x4y3-x3y4)(y2-y1) / [ (x2-x1)(y4-y3) - (x4-x3)(y2-y1) ]
Note that the denominators are the same. They will be ZERO! when the system has no solution. So you may want to check that in another cell and conditionally compute the answer.
Essentially, this formula is derived by solving a system of equations for x and y by hand using generic points (x1,y1), (x2,y2), (x3,y3), and (x4,y4). Easier yet, is solving the system by hand using well developed linear algebra concepts.
Wikipedia outlines this procedure well: Line-line intersection.
Also, this website describes all the different formulas and lets you put in whatever data you have in any mixed format and provides many details of the solutions: Everything about 2 lines.
Here's a matrix based solution:
x - y = -3
0.5*x - y = 0
Written as a matrix equation (I apologize for the poor typesetting):
| 1.0 -1.0 |{ x } { -3 }
| 0.5 -1.0 |{ y } = { 0 }
You can invert this matrix or use LU decomposition to solve it to get the answer. That method will work for any number of cases where you have one equation for each unknown.
This is easy to do by hand:
Subtract the second equation from the first: 0.5*x = -3
Divide both sides by 0.5: x = -6
Substitute this result into the other equation: y = 0.5*x = -3

Differentiating a scalar with respect to matrix

I have a scalar function which is obtained by iterative calculations. I wish to differentiate(find the directional derivative) of the values with respect to a matrix elementwise. How should I employ the finite difference approximation in this case. Does diff or gradient help in this case. Note that I only want numerical derivatives.
The typical code that I would work on is:
n=4;
for i=1:n
for x(i)=-2:0.04:4;
for y(i)=-2:0.04:4;
A(:,:,i)=[sin(x(i)), cos(y(i));2sin(x(i)),sin(x(i)+y(i)).^2];
B(:,:,i)=[sin(x(i)), cos(x(i));3sin(y(i)),cos(x(i))];
R(:,:,i)=horzcat(A(:,:,i),B(:,:,i));
L(i)=det(B(:,:,i)'*A(:,:,i)B)(:,:,i));
%how to find gradient of L with respect to x(i), y(i)
grad_L=tr((diff(L)/diff(R)')*(gradient(R))
endfor;
endfor;
endfor;
I know that the last part for grad_L would syntax error saying the dimensions don't match. How do I proceed to solve this. Note that gradient or directional derivative of a scalar functionf of a matrix variable X is given by nabla(f)=trace((partial f/patial(x_{ij})*X_dot where x_{ij} denotes elements of matrix and X_dot denotes gradient of the matrix X
Both your code and explanation are very confusing. You're using an iteration of n = 4, but you don't do anything with your inputs or outputs, and you overwrite everything. So I will ignore the n aspect for now since you don't seem to be making any use of it. Furthermore you have many syntactical mistakes which look more like maths or pseudocode, rather than any attempt to write valid Matlab / Octave.
But, essentially, you seem to be asking, "I have a function which for each (x,y) coordinate on a 2D grid, it calculates a scalar output L(x,y)", where the calculation leading to L involves multiplying two matrices and then getting their determinant. Here's how to produce such an array L:
X = -2 : 0.04 : 4;
Y = -2 : 0.04 : 4;
X_indices = 1 : length(X);
Y_indices = 1 : length(Y);
for Ind_x = X_indices
for Ind_y = Y_indices
x = X(Ind_x); y = Y(Ind_y);
A = [sin(x), cos(y); 2 * sin(x), sin(x+y)^2];
B = [sin(x), cos(x); 3 * sin(y), cos(x) ];
L(Ind_x, Ind_y) = det (B.' * A * B);
end
end
You then want to obtain the gradient of L, which, of course, is a vector output. Now, to obtain this, ignoring the maths you mentioned for a second, if you're basically trying to use the gradient function correctly, then you just use it directly onto L, and specify the grid X Y used for it to specify the spacings between the different elements in L, and collect its output as a two-element array, so that you capture both the x and y vector-components of the gradient:
[gLx, gLy] = gradient(L, X, Y);

Plotting a function in scilab

can you help me, I 'm trying to plot the function y=1/x in scilab,
the graph that throws me is incorrect
x = [1:1:10]';
y = 1./x;
plot(x,y)
and throws me these results
y=
0.0025974
0.0051948
0.0077922
0.0103896
0.0129870
0.0155844
0.0181818
0.0207792
0.0233766
0.0259740
and this result is wrong , as would be the code ,
Thanks for the help :)
Write
y = 1 ./ x;
instead of
y = 1./x;
From the documentation (emphasis is mine):
a ./ b is the matrix with entries a(i,j)/ b(i,j). If b is scalar (1x1 matrix) this operation is the same as a./b*ones(a). (Same convention if a is a scalar).
Remark that 123./b is interpreted as (123.)/b. In this cases dot is part of the number not of the operator.

Resources