How to use symprod with symbolic arrays? - octave

I would like to have this equation solved symbolically:
x_i = x_0 + \prod_{j = 0}^{i-1}(a_{3-j})
I wrote the following script, which works until I call symprod:
try
pkg load symbolic
end
a = sym('a', [1 3]);
syms x0 i
x0*symprod(a(i), i, [1 3])
The error message says:
error: subscript indices must be integers or boolean
However, this works:
a(2)
ans = (sym) a12
What is wrong with my code?
(I also tried with Matlab Symbolic Toolbox; does not work either, but error message is different.)

The problem is already with the expression a(i), such indexing is not possible:
>> a(i)
error: subscript indices must be integers or boolean
In a situation where a are the integer indices, you are probably better off using prod:
>> prod(a)
ans = (sym) a₁₁⋅a₁₂⋅a₁₃
An alternative is to work with functions:
>> syms fa(i)
>> e=x0*symprod(fa(i), i, [1 3])
e = (sym) x₀⋅fa(1)⋅fa(2)⋅fa(3)

Related

Non-linear fit Gnu Octave

I have a problem in performing a non linear fit with Gnu Octave. Basically I need to perform a global fit with some shared parameters, while keeping others fixed.
The following code works perfectly in Matlab, but Octave returns an error
error: operator *: nonconformant arguments (op1 is 34x1, op2 is 4x1)
Attached my code and the data to play with:
clear
close all
clc
pkg load optim
D = dlmread('hd', ';'); % raw data
bkg = D(1,2:end); % 4 sensors bkg
x = D(2:end,1); % input signal
Y = D(2:end,2:end); % 4 sensors reposnse
W = 1./Y; % weights
b0 = [7 .04 .01 .1 .5 2 1]; % educated guess for start the fit
%% model function
F = #(b) ((bkg + (b(1) - bkg).*(1-exp(-(b(2:5).*x).^b(6))).^b(7)) - Y) .* W;
opts = optimset("Display", "iter");
lb = [5 .001 .001 .001 .001 .01 1];
ub = [];
[b, resnorm, residual, exitflag, output, lambda, Jacob\] = ...
lsqnonlin(F,b0,lb,ub,opts)
To give more info, giving array b0, b0(1), b0(6) and b0(7) are shared among the 4 dataset, while b0(2:5) are peculiar of each dataset.
Thank you for your help and suggestions! ;)
Raw data:
0,0.3105,0.31342,0.31183,0.31117
0.013229,0.329,0.3295,0.332,0.372
0.013229,0.328,0.33,0.33,0.373
0.021324,0.33,0.3305,0.33633,0.399
0.021324,0.325,0.3265,0.333,0.397
0.037763,0.33,0.3255,0.34467,0.461
0.037763,0.327,0.3285,0.347,0.456
0.069405,0.338,0.3265,0.36533,0.587
0.069405,0.3395,0.329,0.36667,0.589
0.12991,0.357,0.3385,0.41333,0.831
0.12991,0.358,0.3385,0.41433,0.837
0.25368,0.393,0.347,0.501,1.302
0.25368,0.3915,0.3515,0.498,1.278
0.51227,0.458,0.3735,0.668,2.098
0.51227,0.47,0.3815,0.68467,2.124
1.0137,0.61,0.4175,1.008,3.357
1.0137,0.599,0.422,1,3.318
2.0162,0.89,0.5335,1.645,5.006
2.0162,0.872,0.5325,1.619,4.938
4.0192,1.411,0.716,2.674,6.595
4.0192,1.418,0.7205,2.691,6.766
8.0315,2.34,1.118,4.195,7.176
8.0315,2.33,1.126,4.161,6.74
16.04,3.759,1.751,5.9,7.174
16.04,3.762,1.748,5.911,7.151
32.102,5.418,2.942,7.164,7.149
32.102,5.406,2.941,7.164,7.175
64.142,7.016,4.478,7.174,7.176
64.142,7.018,4.402,7.175,7.175
128.32,7.176,6.078,7.175,7.176
128.32,7.175,6.107,7.175,7.173
255.72,7.165,7.162,7.165,7.165
255.72,7.165,7.164,7.166,7.166
511.71,7.165,7.165,7.165,7.165
511.71,7.165,7.165,7.166,7.164
Giving the function definition above, if you call it by F(b0) in the command windows, you will get a 34x4 matrix which is correct, since variable Y has the same size.
In that way I can (in theory) compute the standard formula for lsqnonlin (fit - measured)^2

How to correctly calculate a nonlinear function and plot its graph in Octave?

Goal: Plot the graph using a non-linear function.
Function and graph
This is my first time working at Octave. To plot the graph, I need to calculate a function in the range Fx (0.1 ... 10).
I tried to implement this by looping the function through the for loop, writing the results to an array (x-axis - Fn, y-axis - function value), then loading the arrays into the plot() function.
Fn = 1
Ln = 5
Q = 0.5
function retval = test (Fn, Ln, Q)
# Fn squared (for common used)
Fn = Fn^2
# Node A + Node B
nodeA = Fn * (Ln - 1)
nodeB = (Ln * Fn - 1)^2 + Fn * (Fn - 1)^2 * (Ln - 1)^2 * Q^2
nodeB = sqrt(nodeB)
# Result
result = nodeA / nodeB
retval = result
return;
endfunction
frequencyArray = {}
gainArray = {}
fCount = 1
gCount = 1
for i = 0:0.5:5
# F
Fn = i
frequencyArray{fCount} = Fn
fCount = fCount + 1
# G
gainArray{gCount} = test(Fn, Ln, Q)
gCount = gCount + 1
end
plot(frequencyArray, gainArray);
As a result, I get an error about the format of the arrays.
>> plot(frequencyArray, gainArray);
error: invalid value for array property "xdata"
error: __go_line__: unable to create graphics handle
error: called from
__plt__>__plt2vv__ at line 495 column 10
__plt__>__plt2__ at line 242 column 14
__plt__ at line 107 column 18
plot at line 223 column 10
In addition to the error, I believe that these tasks are solved in more correct ways, but I did not quite understand what to look for.
Questions:
Did I choose the right way to solve the problem? Are there any more elegant ways?
How can I fix this error?
Thank you!
If I have correctly interpreted what you are trying to do, the following should work. Firstly, you need to use the term-by-term versions of all arithmetic operators that act on Fn. These are the same as the normal operators except preceded by a dot. Next, you need to put Fn equal to a vector containing the x-values of all the points you wish to plot and put Q equal to a vector containing the values of Q for which you want to draw curves. Use a for-loop to loop through the values of Q and plot a single curve in each iteration of the loop. You don't need a loop to plot each curve because Octave will apply your "test" function to the whole Fn vector and return the result as a vector of the same size. To plot the curves on a log axis, use the function "semilogx(x, y)" insetad of "plot(x, y)". To make the plots appear on the same figure, rather than separate ones put "hold on" before the loop and "hold off" afterwards. You used cell arrays instead of vectors in your for-loop, which the plotting functions don't accept. Also, you don't need an explicit return statement in an Octave function.
The following code produces a set of curves that look like the ones in the figure you pasted in your question:
Ln = 5
function result = test (Fn, Ln, Q)
# Fn squared (for common used)
Fn = Fn.^2;
# Node A + Node B
nodeA = Fn .* (Ln - 1);
nodeB = (Ln .* Fn .- 1).^2 + Fn .* (Fn .- 1).^2 .* (Ln - 1)^2 * Q^2;
nodeB = sqrt(nodeB);
# Result
result = nodeA ./ nodeB;
endfunction
Fn = linspace(0.1, 10, 500);
Q = [0.1 0.2 0.5 0.8 1 2 5 8 10];
hold on
for q = Q
K = test(Fn, Ln, q);
semilogx(Fn, K);
endfor
hold off

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 two non-linear equations in 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

How do I assign variables in matrices?

I can't make matrices with variables in it for some reason. I get following message.
>>> A= [a b ;(-1-a) (1-b); (1+a) b]
error: horizontal dimensions mismatch (2x3 vs 1x1)
Why is it? Please show me correct way if I'm wrong.
In Matlab you first need to assign a variable before you can use it,
a = 1;
b = a+1;
This will thus give an error,
clear;
b = a+1; % ERROR! Undefined function or variable 'a
Matlab does never accept unassigned variables. This is because, on the lowest level, you do not have a. You will have machine code which is assgined the value of a. This is handled by the JIT compiler in Matlab, so you do not need to worry about this though.
If you want to use something as the variable which you have in maths you can specifically express this to matlab. The object is called a sym and the syntax that define the sym x to a variable xis,
syms x;
That said, you can define a vector or a matrix as,
syms a b x y; % Assign the syms
A = [x y]; % Vector
B = A= [a b ;(-1-a) (1-b); (1+a) b]; % Matrix.
The size of a matrix can be found with size(M) or for dim n size(M,n). You can calcuate the matrix product M3=M1*M2 if and only if M1 have the size m * n and M2 have the size n * p. The size of M3 will then be m * p. This will also mean that the operation A^N = A * A * ... is only allowed when m=n so to say, the matrix is square. This can be verified in matlab by the comparison,
syms a b
A = [a,1;56,b]
if size(A,1) == size(A,2)
disp(['A is a square matrix of size ', num2str(size(A,1)]);
else
disp('A is not square');
end
These are the basic rules for assigning variables in Matlab as well as for matrix multiplication. Further, a google search on the error error: 'x' undefined does only give me octave hits. Are you using octave? In that case I cannot guarantee that you can use sym objects or that the syntaxes are correct.