Plotting function with sums - matplotlib

However I try to plot a function including a sum I get errors. CanĀ“t find any example anywhere.
using PyPlot
x = range(0,stop=2,length=10)
f(x) = x + 1
plot(x,f(x))
for example gives me:
MethodError: no method matching +(::StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}, ::Int64)

The problem is not the plotting. The problem is that you try to add a number (1) to a range (x). This is also what the error message states. You need to do it element-wise. Like in e.g. matlab this is achieved with .-operations.
There are two possibilities for you in this example.
either f(x) = x .+ 1; plot(x,f(x))
or f(x) = x + 1; plot(x,f.(x))
Take a look at https://docs.julialang.org/en/v1/manual/mathematical-operations/#man-dot-operators-1

Related

Julia - Defining a Linear Programming Problem with MathOptInterface

I'd like to write a LP problem in the standard format with MatOptInterface, e.i.:
min c'*x
S.t A*x .== b
x >= 0
Now, how can one write this problem with MathOptInterface? I'm having many issues, one of them is how to define the variable "model". For example, if I try to run:
x = add_variables(model,3)
I first would need to declare this model variable. But I don't know how one is supposed to do this on MathOptInterface.
IIUC in your situation model has to be an argument to be specified by the user of your function.
The user can then pass GLPK.Optimizer(), Tulip.Optimizer() or any other optimizer inheriting from MathOptInterface.AbstractOptimizer.
See e.g. Manual#A complete example.
Alternatively you can look at MOI.Utilities.Model but I don't know how to get an optimizer to solve that model.
Here is how to implement the LP solver for standard Simplex format:
function SolveLP(c,A,b,model::MOI.ModelLike)
x = MOI.add_variables(model, length(c));
MOI.set(model, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(),
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(c, x), 0.0))
MOI.set(model, MOI.ObjectiveSense(), MOI.MIN_SENSE)
for xi in x
MOI.add_constraint(model, MOI.SingleVariable(xi), MOI.GreaterThan(0.0))
end
for (i,row) in enumerate(eachrow(A))
row_function = MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(row, x), 0.0);
MOI.add_constraint(model, row_function, MOI.EqualTo(b[i]))
end
MOI.optimize!(model)
p = MOI.get(model, MOI.VariablePrimal(), x);
return p
end
For the model, just choose something like GLPK.Optimizer()

Matplotlib: Plot a function with multiple defintions

How do I plot e.g. a function f(x) = x for 0 < x < 1 and f(x) = 1 for x >= 1?
Thanks in advance!
EDIT:
Okay, I have thought for a while and found a solution for the given function, but I'd really like to find a more generic solution. Maybe like f=f1+f2+...fn, where fi is the function in domain i and then plot f alltogehter.
f = 0.5*(1*(1-np.sign(1-x))+x*(1-np.sign(x-1)))
Matplotlib doesn't care where your data comes from: you can either make lists from two different functions and combine them, or call a function with a conditional in it. The most mathematically appealing choice is probably
def f(x):
return 1 if x>=1 else 0 if x>0 else ...
Of course, if you care only about x>0, your function can be computed just as x>=1, which can be used as a number already.

How to define a function with 3 variables in GNUPLOT

I am new to GNUPLOT. I am trying to plot 3d vector fields. However I am having trouble defining a function of three variables f(x,y,z). Can anyone show me how to do this correctly?
Defining your own functions in gnuplot is pretty intuitive. According to the gnuplot documentation the syntax is as follows
<func-name>( <dummy1> {,<dummy2>} ... {,<dummy5>} ) = <expression>
Examples:
w = 2
q = floor(tan(pi/2 - 0.1))
f(x) = sin(w*x)
sinc(x) = sin(pi*x)/(pi*x)
delta(t) = (t == 0)
ramp(t) = (t > 0) ? t : 0
min(a,b) = (a < b) ? a : b
comb(n,k) = n!/(k!*(n-k)!)
len3d(x,y,z) = sqrt(x*x+y*y+z*z)
plot f(x) = sin(x*a), a = 0.2, f(x), a = 0.4, f(x)
There is also a large set of built-in mathematical functions which you can use (in the definition of your own function).
For piecewise defined functions you can use the fact that undefined values are ignored. Therefore, the function
y(x) = x < 0 ? 1/0 : x
is only defined for positive arguments.
Powers are defined by **. Hence f(x)=x*x is identical to f(x)=x**2
If you have still problems in defining your own function, please feel free to ask. (Shouldn't a 3d-function only depend on x and y, i.e., f(x,y)=...?)
For examples of 3d plots, also see the gnuplot demo site.

sympy subs in matrix doesn't change the values

I have a symbolic matrix that I want to differentiate. I have to substitute numeric values to some of the vars and then to solve with respect to 6 unknowns. My problem is that defining the element of matrix A by lambda and subistituting with subs doesn't change any value in the matrix. When I want retrieve the type of matrix in fact it's shown that it's immutable, which seems quite odd. Here's the code:
def optimalF1():
x,y,z=symbols('x y z', Real=True)
phi,theta,psi=symbols('phi theta psi')
b1x,b1y=symbols('b1x b1y')
b2x,b2y=symbols('b2x b2y')
b3x,b3y=symbols('b3x b3y')
b4x,b4y=symbols('b4x b4y')
b5x,b5y=symbols('b5x b5y')
b6x,b6y=symbols('b6x b6y')
bMat=sym.Matrix(([b1x,b2x,b3x,b4x,b5x,b6x],
[b1y,b2y,b3y,b4y,b5y,b6y],[0,0,0,0,0,0]))
mov=np.array([[x],[y],[z]])
Pi=np.repeat(mov,6,axis=1)
sym.pprint(Pi)
print 'shape of thing Pi', np.shape(Pi)
p1x,p1y,p1z=symbols('p1x,p1y,p1z')
p2x,p2y,p2z=symbols('p2x,p2y,p2z')
p3x,p3y,p3z=symbols('p3x,p3y,p3z')
p4x,p4y,p4z=symbols('p4x,p4y,p4z')
p5x,p5y,p5z=symbols('p5x,p5y,p5z')
p6x,p6y,p6z=symbols('p6x,p6y,p6z')
#legs symbolic array
l1,l2,l3,l4,l5,l6=symbols('l1,l2,l3,l4,l5,l6')
piMat=Matrix(([p1x,p2x,p3x,p4x,p5x,p6x],[p1y,p2y,p3y,\
p4y,p5y,p6y],[p1z,p2z,p3z,p4z,p5z,p6z]))
piMat=piMat.subs('p1z',0)
piMat=piMat.subs('p2z',0)
piMat=piMat.subs('p3z',0)
piMat=piMat.subs('p4z',0)
piMat=piMat.subs('p5z',0)
piMat=piMat.subs('p6z',0)
sym.pprint(piMat)
legStroke=np.array([[l1],[l2],[l3],[l4],[l5],[l6]])
'''redefine the Eul matrix
copy values of Pi 6 times by using np.repeat
'''
r1=[cos(phi)*cos(theta)*cos(psi)-sin(phi)*sin(psi),\
-cos(phi)*cos(theta)*sin(psi)-sin(phi)*cos(psi),\
cos(phi)*sin(theta)]
r2=[sin(phi)*cos(theta)*cos(psi)+cos(phi)*sin(psi),\
-sin(phi)*cos(theta)*sin(psi)+cos(phi)*cos(psi),\
sin(phi)*sin(theta)]
r3= [-sin(theta)*cos(psi),sin(theta)*sin(psi),cos(theta)]
EulMat=Matrix((r1,r2,r3))
print(EulMat)
uvw=Pi+EulMat*piMat
print 'uvw matrix is:\n', uvw, np.shape(uvw)
# check thisout -more elegant and compact form
A=Matrix(6,1,lambda j,i:((uvw[0,j]- \
bMat[0,j])**2+(uvw[1,j]-bMat[1,j])**2+\
(uvw[2,j]-bMat[2,j])**2)-legStroke[j]**2)
print'A matrix before simplification:\n ', A
B=simplify(A)
B=B.subs({'x':1.37,'y':0,'z':0,theta:-1.37,phi:0})
print'A matrix form after substituting:\n',B
So comparing A and B leads to the same output. I don't understand why!
When you use subs with variables that have assumptions, you have to use the symbols not strings. Using strings causes a new generic symbol to be created which does not match the symbol having assumptions so the subs fails.
>>> var('x')
x
>>> var('y',real=True)
y
>>> (x+y).subs('x',1).subs('y',2)
y + 1
Note, too, that to make real symbols you should use real=True not Real=True (lower case r).

find ranges to create Uniform histogram

I need to find ranges in order to create a Uniform histogram
i.e: ages
to 4 ranges
data_set = [18,21,22,24,27,27,28,29,30,32,33,33,42,42,45,46]
is there a function that gives me the ranges so the histogram is uniform?
in this case
ranges = [(18,24), (27,29), (30,33), (42,46)]
This example is easy, I'd like to know if there is an algorithm that deals with complex data sets as well
thanks
You are looking for the quantiles that split up your data equally. This combined with cutshould work. So, suppose you want n groups.
set.seed(1)
x <- rnorm(1000) # Generate some toy data
n <- 10
uniform <- cut(x, c(-Inf, quantile(x, prob = (1:(n-1))/n), Inf)) # Determine the groups
plot(uniform)
Edit: now corrected to yield the correct cuts in the ends.
Edit2: I don't quite understand the downvote. But this also works in your example:
data_set = c(18,21,22,24,27,27,28,29,30,32,33,33,42,42,45,46)
n <- 4
groups <- cut(data_set, breaks = c(-Inf, quantile(data_set, prob = 1:(n-1)/n), Inf))
levels(groups)
With some minor renaming nessesary. For slightly better level names, you could also put in min(x) and max(x) instead of -Inf and Inf.