Solving two non-linear equations in Octave - octave

I am trying to solve the following two equations using Octave:
eqn1 = (wp/Cwc)^(2*N) - (1/10^(0.1*Ap))-1 == 0;
eqn2 = (ws/Cwc)^(2*N) - (1/10^(0.1*As))-1 == 0;
I used the following code:
syms Cwc N
eqn1 = (wp/Cwc)^(2*N) - (1/10^(0.1*Ap))-1 == 0;
eqn2 = (ws/Cwc)^(2*N) - (1/10^(0.1*As))-1 == 0;
sol = solve(eqn1 ,eqn2, Cwc, N)
ws,wp,As, and Ap are given as 1.5708, 0.31416, 0.5, 45 respectively.
But I am getting the following error:
error: Python exception: NotImplementedError: could not solve
126491*(pi*(3*10**N*sqrt(314311)*pi**(-N)/1223)**(1/N)/2)**(2*N) - 126495
occurred at line 7 of the Python code block:
d = sp.solve(eqs, *symbols, dict=True)
What should I do to solve this?
Edit:
I modified the equations a little bit.
pkg load symbolic
clear all
syms Cwc N
wp = 0.31416
ws = 1.5708
As = 45
Ap = 0.5
eqn2 = N - log10(((1/(10^(0.05*As)))^2)-1)/2*log10(ws/Cwc) == 0;
eqn1 = N - log10(((1/(10^(0.05*Ap)))^2)-1)/2*log10(wp/Cwc) == 0;
sol = solve(eqn1,eqn2,Cwc,N)
And now I am getting this error:
error: Python exception: AttributeError: MutableDenseMatrix has no attribute is_Relational.
occurred at line 3 of the Python code block:
if arg.is_Relational:

Looking at the equations, with unknowns in the base and exponent of the same term, highly suggests there is no symbolic solution to be found. I gave a simplified system (2/x)^y = 4, (3/x)^y = 5 to a couple of symbolic solvers, neither of which got anything from it. So, the only way to solve this is numerically (which makes sense because the four known parameters you have are some floating point numbers anyway). Octave's numeric solver for this purpose is fsolve. Example of usage:
function y = f(x)
Cwc = x(1);
N = x(2);
ws = 1.5708;
wp = 0.31416;
As = 0.5;
Ap = 45;
y = [(wp/Cwc)^(2*N) - (1/10^(0.1*Ap))-1; (ws/Cwc)^(2*N) - (1/10^(0.1*As))-1];
endfunction
fsolve(#f, [1; 1])
(Here, [1; 1] is an initial guess.) The output is
0.31413
0.19796

Related

Plotting function with respect to a keyword argument leads to error in Julia

I have a function which involves bunch of integrals and complicated computations, like the following:
using HCubature
function func(v, x0, y0; rad=1.)
L = hcubature(r->r[1]*v(x0+r[1]*cos(r[2]), y0+r[1]*sin(r[2])), [0., π/2], [rad, π])[1]
R = hcubature(r->r[1]*v(x0+r[1]*cos(r[2]), y0+r[1]*sin(r[2])), [0., 0], [rad, π/2])[1]
return L, R
end
The argument v is a function itself.
When I try to plot the function with respect to the keyword argument rad, I obtain error messages as follows:
x0_, y0_ = 0, 0
rad_ = 0.:0.1:9.
func_array_L = [func(v, x0_, y0_; rad = radius)[1] for radius in rad_]
func_array_R = [func(v, x0_, y0_; rad = radius)[2] for radius in rad_]
plot(rad_, func_array_L)
plot!(rad_, func_array_R)
The error message includes a very long error message: Internal error: encountered unexpected error in runtime: then followed by a long list of directories, and then it comes to the following:
MethodError: no method matching string(::Expr)
The applicable method may be too new: running in world age 3820, while current world is 26290.
Closest candidates are:
string(::Any...) at strings/io.jl:168 (method too new to be called from this world context.)
string(!Matched::String) at strings/substring.jl:152 (method too new to be called from this world context.)
string(!Matched::SubString{String}) at strings/substring.jl:153 (method too new to be called from this world context.)
...
I tried also other methods like declaring another function with rad as the only argument, etc. but none of them worked. How to fix the problem?
Indeed the error message is strange, but the reason is simple. You have not defined the function v. You should define it first, and then all should work as expected.
Additionally note that you have a wrong case in using HCubature (note that u should be lowercase). Also in order for plotting to work you should firs import a plotting package e.g. by using Plots.
EDITS
A basic code that reproduces your problem is:
julia> using HCubature
julia> function func(v, x0, y0; rad=1.)
L = hcubature(r->r[1]*v(x0+r[1]*cos(r[2]), y0+r[1]*sin(r[2])), [0., π/2], [rad, π])[1]
R = hcubature(r->r[1]*v(x0+r[1]*cos(r[2]), y0+r[1]*sin(r[2])), [0., 0], [rad, π/2])[1]
return L, R
end
func (generic function with 1 method)
julia> v = (x,y) -> x
#27 (generic function with 1 method)
julia> x0_, y0_ = 0, 0
(0, 0)
julia> rad_ = 0.:0.1:9.
0.0:0.1:9.0
julia> func_array_L = [func(v, x0_, y0_; rad = radius)[1] for radius in rad_]
Internal error: encountered unexpected error in runtime:
MethodError(f=typeof(Base.string)(), args=(Expr(:<:, :t, :r),), world=0x0000000000000eec)
This seems to be a bug. I reported it here.
A workaround
Now - the way to solve it is to make v type stable. There are three example ways to do it.
Option 1: define it as const:
const v1 = v
and use a comprehension with v1 passed instead of v.
Option 2: wrap it in let block:
func_array_L = let v=v
[func(v, x0_, y0_; rad = radius)[1] for radius in rad_]
end
Option 3: define a function with a name using v:
v2(x,y) = v(x,y)
and use a comprehension with v2 passed instead of v.
Alternatively you could also make x0_ or y0_ to be of constant type (it is enough to fix one of them) to make all work. E.g. this
func_array_L = [func(v, 1, y0_; rad = radius) for radius in rad_]
works as expected.
Additional notes
You have a similar problem if you use map instead of a comprehension if in map you use an anonymous function:
map(radius -> func(v, x0_, y0_; rad = radius)[1], rad_)
and also a normal function that has a name produces the same error:
v3(radius) = func(v, x0_, y0_; rad = radius)[1]
map(v3, rad_)
but it starts to work if you make an internal function that is introduced into a method-table:
v3(radius) = (tmp(x...) = v(x...); func(tmp, x0_, y0_; rad = radius)[1])
and now map(v3, rad_) works as expected.

Please specify the error in this octave code

So I am trying to solve this problem from coursera regarding onevsAll classification. It comes under the ml course under Andrew NG. I am not able to find mistake in my code and it keeps showing this error
error: fmincg: operator +: nonconformant arguments (op1 is 401x1, op2 is 4x1)
error: called from
fmincg at line 87 column 5
oneVsAll at line 60 column 13
ex3 at line 77 column 13
I have tried reading the fmincg code but I cannot understand the problem.
function [all_theta] = oneVsAll(X, y, num_labels, lambda)
% Some useful variables
m = size(X, 1);
n = size(X, 2);
% You need to return the following variables correctly
all_theta = zeros(num_labels, n + 1);
% Add ones to the X data matrix
X = [ones(m, 1) X];
for c = 1:num_labels
initial_theta = zeros(n+1,1) ;
options = optimset('GradObj', 'on', 'MaxIter', 50);
[theta] = fmincg (#(t)(lrCostFunction(t, X, (y == c), lambda)),initial_theta, options);
all_theta(c, :) = theta;
end;
Program is showing error mentioned above regarding the fmincg file.

Octave - System of differential equations with lsode

here is my problem. I'm trying to solve a system of two differential equations thanks to the two functions below. The part of the code that give me some trouble is the variable "rho". "rho" is a function which values are given from a file and that I tried to put in the the variable rho.
function [xdot]=f2(x,t)
# Parameters of the equations
t=[1:1:35926];
x = dlmread('data_txt.txt');
rho=x(:,4);
beta = 0.68*10^-2;
g = 1.5;
l = 1.6;
# Definition of the system of 2 ODE's :
xdot(1) = ((rho-beta)/g)*x(1) + l*x(2);
xdot(2) = (beta/g)*x(1)-l*x(2);
endfunction
.
# Initial conditions for the two variables :
x0 = [0;1];
# Definition of the time-vector -> (initial time,temporal mesh,final time) :
t = linspace (1, 10, 10000);
# Resolution with the lsode routine :
x = lsode ("f2", x0, t);
# Plot of the two curves :
plot (t,x);
When I run my code, I get the following error:
>> resolution_effective2
error: f2: A(I) = X: X must have the same size as I
error: called from
f2 at line 34 column 9
resolution_effective2 at line 8 column 3
error: lsode: evaluation of user-supplied function failed
error: called from
resolution_effective2 at line 8 column 3
error: lsode: inconsistent sizes for state and derivative vectors
error: called from
resolution_effective2 at line 8 column 3
I know that my error comes from a mismatch of size between some variable but I have been looking for the error for days now and I don't see. Could someone try to give and explain me an effective correction ?
Thank you
The error might come from your function f2. Its first argument x should have the same dimension as x0 since x0 is the initial condition of x.
In your case, whatever you intent to be the first argument of f2 is ignored since in your function you do x = dlmread('data_txt.txt'); this seems to be a mistake.
Then, xdot(1) = ((rho-beta)/g)*x(1) + l*x(2); will be a problem since rho is a vector.
You need to check the dimensions of x and rho.

Solving system of ODEs using Octave

I am trying to solve a system of two ODEs using Octave, and in particular the function lsode.
The code is the following:
function xdot = f (x,t)
a1=0.00875;
a2=0.075;
b1=7.5;
b2=2.5;
d1=0.0001;
d2=0.0001;
g=4*10^(-8);
K1=5000;
K2=2500;
n=2;
m=2;
xdot = zeros(2,1);
xdot(1) = a1+b1*x(1)^n/(K1^n+x(1)^n)-g*x(1)*x(2)-d1*x(1);
xdot(2) = a2+b2*x(1)^m/(K2^m+x(1)^m)-d2*x(2);
endfunction
t = linspace(0, 5000, 200)';
x0 = [1000; 1000];
x = lsode ("f", x0, t);
set term dumb;
plot(t,x);
I am getting continuously the same error, that "x" is not defined, and I do not know why. The error is the following:
warning: function name 'f' does not agree with function file name '/home /Simulation 1/sim.m'
error: 'x' undefined near line 17 column 17
error: called from
sim at line 17 column 9
It would we great that any of you could help me with this code.
You have two errors. One, you are not saving your source code with the proper name. Two, variable "x" is a vector, and nothing in your script indicates that. You should add a line "x = zeros(1,2);" right after "xdot = zeros(2,1);".
Try the following code:
function ODEs
t = linspace(0, 5000, 200);
x0 = [1000; 1000];
x = lsode (#f, x0, t);
fprintf('t = %e \t\t x = %e\n',t,x);
endfunction
function xdot = f(x,t)
a1=0.00875;
a2=0.075;
b1=7.5;
b2=2.5;
d1=0.0001;
d2=0.0001;
g=4*10^(-8);
K1=5000;
K2=2500;
n=2;
m=2;
xdot = zeros(2,1);
x = zeros(1,2);
xdot(1) = a1+b1*x(1)^n/(K1^n+x(1)^n)-g*x(1)*x(2)-d1*x(1);
xdot(2) = a2+b2*x(1)^m/(K2^m+x(1)^m)-d2*x(2);
endfunction
Save it as ODEs.m and execute it. It does not plot anything, but gives you an output with the results for the t range you supplied.

How to use Newton-Raphson method in matlab to find an equation root?

I am a new user of MATLAB. I want to find the value that makes f(x) = 0, using the Newton-Raphson method. I have tried to write a code, but it seems that it's difficult to implement Newton-Raphson method. This is what I have so far:
function x = newton(x0, tolerance)
tolerance = 1.e-10;
format short e;
Params = load('saved_data.mat');
theta = pi/2;
zeta = cos(theta);
I = eye(Params.n,Params.n);
Q = zeta*I-Params.p*Params.p';
% T is a matrix(5,5)
Mroot = Params.M.^(1/2); %optimization
T = Mroot*Q*Mroot;
% Find the eigenvalues
E = real(eig(T));
% Find the negative eigenvalues
% Find the smallest negative eigenvalue
gamma = min(E);
% Now solve for lambda
M_inv = inv(Params.M); %optimization
zm = Params.zm;
x = x0;
err = (x - xPrev)/x;
while abs(err) > tolerance
xPrev = x;
x = xPrev - f(xPrev)./dfdx(xPrev);
% stop criterion: (f(x) - 0) < tolerance
err = f(x);
end
% stop criterion: change of x < tolerance % err = x - xPrev;
end
The above function is used like so:
% Calculate the functions
Winv = inv(M_inv+x.*Q);
f = #(x)( zm'*M_inv*Winv*M_inv*zm);
dfdx = #(x)(-zm'*M_inv*Winv*Q*M_inv*zm);
x0 = (-1/gamma)/2;
xRoot = newton(x0,1e-10);
The question isn't particularly clear. However, do you need to implement the root finding yourself? If not then just use Matlab's built in function fzero (not based on Newton-Raphson).
If you do need your own implementation of the Newton-Raphson method then I suggest using one of the answers to Newton Raphsons method in Matlab? as your starting point.
Edit: The following isn't answering your question, but is just a note on coding style.
It is useful to split your program up into reusable chunks. In this case your root finding should be separated from your function construction. I recommend writing your Newton-Raphson method in a separate file and call this from the script where you define your function and its derivative. Your source would then look some thing like:
% Define the function (and its derivative) to perform root finding on:
Params = load('saved_data.mat');
theta = pi/2;
zeta = cos(theta);
I = eye(Params.n,Params.n);
Q = zeta*I-Params.p*Params.p';
Mroot = Params.M.^(1/2);
T = Mroot*Q*Mroot; %T is a matrix(5,5)
E = real(eig(T)); % Find the eigen-values
gamma = min(E); % Find the smallest negative eigen value
% Now solve for lambda (what is lambda?)
M_inv = inv(Params.M);
zm = Params.zm;
Winv = inv(M_inv+x.*Q);
f = #(x)( zm'*M_inv*Winv*M_inv*zm);
dfdx = #(x)(-zm'*M_inv*Winv*Q*M_inv*zm);
x0 = (-1./gamma)/2.;
xRoot = newton(f, dfdx, x0, 1e-10);
In newton.m you would have your implementation of the Newton-Raphson method, which takes as arguments the function handles you define (f and dfdx). Using your code given in the question, this would look something like
function root = newton(f, df, x0, tol)
root = x0; % Initial guess for the root
MAXIT = 20; % Maximum number of iterations
for j = 1:MAXIT;
dx = f(root) / df(root);
root = root - dx
% Stop criterion:
if abs(dx) < tolerance
return
end
end
% Raise error if maximum number of iterations reached.
error('newton: maximum number of allowed iterations exceeded.')
end
Notice that I avoided using an infinite loop.