I am trying to solve a nonlinear equation with Julia,
I have the following nonlinear equation
Nfoc(k,k1,z,n)=(1-α)*exp(z)*(k/n)^α/(exp(z)*(k^α)*(n^(1-α))+k*(1-δ)-k1) - A/(1-n)
and I have a grid of values for k,k1 and z and I am trying to find the values of x that are the roots of this equation for each k,k1, and z, by using this loop:
MatrixN=zeros(nkk,M,nkk)
for i=1:nkk,j=1:M
for i2=1:nkk
MatrixN[i,j,i2]=roots(Nfoc[K[i],K[i2],z(j),n])
end
end
However, its obvious that the command roots its not functioning.
I would deeply appreciate any help in the less techical way possible!
I don't have enough knowledge to work on your use case, but in general, one way to find roots of a parametric function could be:
using FastAnonymous # Creating efficient "anonymous functions" in Julia
using Roots
f(x,k,k1,z,n) = exp(x) - x^4 + k + k1 + z + n
function f_gen(k,k1,z,n)
#anon x -> f(x,k,k1,z,n)
end
fzero(f_gen(0,0,0,0), 1) # => finds x so f(x,0,0,0,0) = 0 using a derivative free method
Related
I have a curvefit problem
I have two functions
y = ax+b
y = ax^2+bx-2.3
I have one set of data each for the above functions
I need to find a and b using least square method combining both the functions
I was using fminsearch function to minimize the sum of squares of errors of these two functions.
I am unable to use this method in lsqcurvefit
Kindly help me
Regards
Ram
I think you'll need to worry less about which library routine to use and more about the math. Assuming you mean vertical offset least squares, then you'll want
D = sum_{i=1..m}(y_Li - a x_Li + b)^2 + sum_{i=j..n}(y_Pj - a x_Pj^2 - b x_Pj + 2.3)^2
where there are m points (x_Li, y_Li) on the line and n points (x_Pj, y_Pj) on the parabola. Now find partial derivatives of D with respect to a and b. Setting them to zero provides two linear equations in 2 unknowns, a and b. Solve this linear system.
y = ax+b
y = ax^2+bx-2.3
In order to not confuse y of the first equation with y of the second equation we use distinct notations :
u = ax+b
v = ax^2+bx+c
The method of linear regression combined for the two functions is shown on the joint page :
HINT : If you want to find by yourself the matrixial equation appearing above, follow the Gene's answer.
I try to solve some matrix calculus problem with sympy and get stuck at the solver after differentiation with respect to a vector.
As a short example let's take ordinary least squares regression.
E.g. the sum of the squared differences between target y and prediction y_hat. Where the prediction y_hat = X.T * w is linear combination and thus a matrix vector multiplication.
We therefore want to minimize the LMS Error with respect to the weight vector w.
By hand we can derive that from:
Err(w) = norm(y - X.T * w)^2
follows after differentiation, setting to zero and solving for w
w_opt = (X*X.T)^-1 * X * y
How can we derive w_opt using sympy?
My rather naïve approach was:
from sympy import *
# setup matrix and vectors
X = MatrixSymbol('X',3,5)
y = MatrixSymbol('y',5,1)
w = MatrixSymbol('w',3,1)
# define error function
E = (y - X.T*w).T * (y - X.T*w)
# derivate
Edw = [E.diff(wi) for wi in w]
# solve for w
solve(Edw,w)
At solve(Edw,w) however i get the attribute error: 'Mul' object has no attribute 'shape'
I also tried to set E.as_explicit() before differentiating. This however resultet in the attribute error: 'str' object has no attribute 'is_Piecewise'
I know by calculating by hand, that after derivation the result should be -2*X*y + 2*X*X.T*w. The derivation in Edw is listed but not performed. How can I verify this step in between? My first guess was the .doit() method, which unfortunately is not defined in that case.
I want to define a function which deals with matrices for example..
If I have a characteristic polynomial of a matrix with me and I want to check the cayley hamilton theorem.. What can be done better?
var('x')
f(x)=2x^2+x+3 # this the characteristic polynomial of $A$ (say)
print f(A)# this is what I want as an answer..
In the above if I want to replace my x by a matrix what I have to do?
So, ultimate aim is to find define a polynomial which can take matrix
Thanks in advance...
Amazingly, apparently this hasn't come up very often despite having already been mentioned six years ago, so we haven't fixed it.
sage: M = matrix([[1,2],[3,4]])
sage: g(x) = x^2-5*x-2
sage: g(M)
TypeError: no canonical coercion from Full MatrixSpace of 2 by 2 dense matrices over Integer Ring to Callable function ring with argument x
(Doing at least something about this is Trac 15487.)
However, try using this trick. The problem is only with symbolic expressions, not polynomials.
sage: M = matrix([[1,2],[3,4]])
sage: f = M.charpoly()
sage: f.subs(x=M)
[0 0]
[0 0]
Edit: in general, try something like this.
M = matrix([[1,2],[3,4]])
R.<t> = PolynomialRing(SR)
f = t^2+t+1
f(M)
I am trying to understand how I can write an algorithm to solve the formula written at the end of this answer
I know simple equations systems may be solved through matrices when you have Ax=b you can solve with x = A^(-1)b but this is a little more complicated for me
I think I should come to a form such as A vec(c) = b but I don't have idea how to deal with sums and dot products..
Use the last formula in the linked answer.To simplify it, normalize direction vectors d(i) (to exclude denominator)
Sum[i=1..N] (c - a(i) - d(i) * DotProduct(c-a(i), d(i))) = 0
Sum[i=1..N] (c - a(i) -
d(i) * ((c.x-a(i).x) * d(i).x + (c.y-a(i).y) * d(i).y +(c.z-a(i).z) * d(i).z)) = 0
etc
You have a system of three linear equations. You can solve this system with simple elimination method (which is close to the school approach for solving eq. systems)
Wikipedia says we can approximate Bark scale with the equation:
b(f) = 13*atan(0.00076*f)+3.5*atan(power(f/7500,2))
How can I divide frequency spectrum into n intervals of the same length on Bark scale (interval division points will be equidistant on Bark scale)?
The best way would be to analytically inverse function (express x by function of y). I was trying doing it on paper but failed. WolframAlpha search bar couldn't do it also. I tried Octave finverse function, but I got error.
Octave says (for simpler example):
octave:2> x = sym('x');
octave:3> finverse(2*x)
error: `finverse' undefined near line 3 column 1
This is finverse description from Matlab: http://www.mathworks.com/help/symbolic/finverse.html
There could be also numerical way to do it. I can imagine that you just start from dividing the y axis equally and search for ideal division by binary search. But maybe there are some existing tools that do it?
You need to numerically solve this equation (there is no analytical inverse function). Set values for b equally spaced and solve the equation to find the various f. Bissection is somewhat slow but a very good alternative is Brent's method. See http://en.wikipedia.org/wiki/Brent%27s_method
This function can't be inverted analytically. You'll have to use some numerical procedure. Binary search would be fine, but there are more efficient ways to do these sorts of things: look into root-finding algorithms. You can apply your algorithm of choice to the equation b(f) = f_n for each of the frequency interval endpoints f_n.
Just so you know, in (say) octave to implement rpsmi's or David Zaslavsky's answer, you'd do something like this:
global x0 = 0.
function res = b(f)
global x0
res = 13*atan(0.00076*f)+3.5*atan(power(f/7500,2)) - x0
end
function [intervals, barks] = barkintervals(left, right, n)
global x0
intervals = linspace(left, right, n);
barks = intervals;
for i = 1:n
x0 = intervals(i);
# 125*x0 is just a crude guess starting point given the values
[barks(i), fval, info] = fsolve('b', 125*x0);
endfor
end
and run it like so:
octave:1> barks
octave:2> [i,bx] = barkintervals(0, 10, 10)
[... lots of output from fsolve deleted...]
i =
Columns 1 through 8:
0.00000 1.11111 2.22222 3.33333 4.44444 5.55556 6.66667 7.77778
Columns 9 and 10:
8.88889 10.00000
bx =
Columns 1 through 6:
0.0000e+00 1.1266e+02 2.2681e+02 3.4418e+02 4.6668e+02 5.9653e+02
Columns 7 through 10:
7.3639e+02 8.8960e+02 1.0605e+03 1.2549e+03
I finally decided not to use the Bark values approximation but ideal values for critical bands centres (defined for n=1..24). I plotted them with gnuplot and on the same graph I plotted arbitrarily chosen values for points of greater density (for the required n>24). I adjusted the points values in Hz till the the both curves were approximately the same.
Of course rpsmi and David Zaslavsky answers are more general and scalable.