The question requires a Lagrange polynomial L(c) to replace the complicated-looking function, f. Also, plot function f and L(c) between [1:0; 10:0]. However, after the code computes the values for k, it cannot seem to create a plot and a graph. What am I doing wrong? Attached is the code below. Thank You!
clear
pkg load symbolic
graphics_toolkit('gnuplot')
syms m x
c = []
for i = 1: 0.5 : 10
c = [c,i]
endfor
d = length(c)
k = []
f = 3.* (1 .- ( 8 ./ vpa(pi.^2) .* ((1 ./ cosh(vpa(pi) .* vpa(x) ./ 2)) .+ symsum(1 ./ ((2 .* m .+ 1).^2 .* cosh((2 .* m .+ 1) .* vpa(pi) .* vpa(x) ./ 2)), m,1 ,Inf)))) ./ ((1 .- ( 192 ./ vpa(x) .* vpa(pi.^5)).*(tanh(vpa(pi) .* vpa(x) ./ 2) .+ symsum(tanh((2 .* m .+ 1) .* vpa(pi) .* vpa(x) ./ 2) ./ (2 .* m .+ 1).^5, m,1 ,Inf))));
for i = 1:d
A = (1 - ( 192 / vpa(c(i)) * vpa(pi^5))*(tanh(vpa(pi) * vpa(c(i)) / 2) + symsum(tanh((2 * m + 1) * vpa(pi) * vpa(c(i)) / 2) / (2 * m + 1)^5, m, 1, Inf)))
B = 1 - ( 8 / vpa(pi^2) * ((1 / cosh(vpa(pi) * vpa(c(i)) / 2)) + symsum(1 / ((2 * m + 1)^2 * cosh((2 * m + 1) * vpa(pi) * vpa(c(i)) / 2)), m, 1, Inf)))
K = 3 * B / A
k = [k,K]
endfor
col = c(1)
matrixc = [];
for m = 1:d;
prod = 1;
for t = 1:d
if col == ((m+1)/2)
col = col .+ ((10-1)/(d-1));
endif
sol = (x.-vpa(col))./(vpa((m+1)/2).-vpa(col));
prod = prod*sol;
col = col .+ ((c(2)-c(1))/(d-1));
endfor
h = k(m);
p = vpa(h).*prod;
matrixc = [matrixc,p];
col = 1;
endfor
L=sum(matrixc);
L
ezplot(L,[c(1),c(d)]);
hold on;
k(1)
plot(c,k);
legend('Lagrange Polynomial','K(x)');
xlabel('x-axis');
ylabel('y-axis');```
You are trying to plot a symbolic variable.
I don't know if this is possible in general, but in this particular case at least the conversion is causing problems
Collect the values of the symbolic variable first, by casting to double, and then you can plot as intended:
plot( c, double(k) );
Related
When I used this code, it plots two functions like this:
a = 2;
t0 = 1;
N = 100;
epsilon = 1e-5;
function t = metodoDeNewton(a, t0, N, epsilon)
t = zeros(1, N+1);
t(1) = t0;
for i = 1:N
t(i+1) = t(i) - (t(i).^2 - (a - sin(t(i)))) ./ (2 .* t(i) - cos(t(i)));
if abs(t(i+1) - t(i)) < epsilon
break;
endif
endfor
endfunction
t = metodoDeNewton(a, t0, N, epsilon);
x = 0:0.01:1;
y1 = t;
y2 = a - sin(t);
l = plot(x, y1, x, y2);
legend({'g(a)', 'h(a)'});
xlabel('a');
ylabel('y');
But, when I try to change the x to x = 0:0.01:0.2 the graph's y-axis scale changes and I'm no longer able to see the functions I believe.
How can I fix this, any help would be appreciated!
I am facing trouble in the increasing oscillation on a simple harmonic oscillator using a backward difference. here is my code in Scilab
function [x] = back(h, tf)
k = 2;
m = 1;
i = 2;
t(i - 1) = 0;
x(i - 1) = 10;
v(i - 1) = 0;
t(i) = t(i - 1) + h
v(i) = v(i - 1) - h * (k / m) * x(i - 1)
while t(i) < tf
t(i + 1) = t(i) + h
x(i + 1) = x(i - 1) - 2 * (k / m) * v(i) * h
i = i + 1
end
plot(t, x, 'b');
endfunction
From your code, I suppose that you are trying to implement the velocity-Verlet scheme. Here is its implementation for a simple oscillator with the differential equation:
function [x] = back(h, tf)
k = 2;
m = 1;
t = 0:h:tf;
x(1) = 10;
v(1) = 0;
for i=2:length(t)
x(i) = x(i - 1) + v(i - 1) * h - k / m * x(i-1) * h^2 / 2;
v(i) = v(i - 1) - k / m * (x(i) + x(i-1)) * h / 2;
end
plot(t, x, 'b');
endfunction
[x] = back(0.01, 10)
I'm not quite sure what you are trying to achieve, neither if your math is correct. But assuming that you want to solve the numerical problem of:
//coefficients of:
k = 2.;
m = 1.;
// with an initial condition of:
t(1) = 0.;
x(1) = 10.;
v(1) = 0.;
// time paramters:
N = 50;
tf = 10;
h = tf / 50.;
for ii = 2:N
t(ii) = t(ii - 1) + h;
x(ii) = x(ii - 1) - 2 * (k / m) * v(ii - 1) * h
v(ii) = v(ii - 1) - h * (k / m) * x(ii - 1)
disp(x(ii))
end
plot(t, x, 'b');
will result in:
which doesn't seem right but anyway. Please check your math again.
I've installed and loaded the symbolic package that becomes available from optim package to obtain the syms function (like in MATLAB) but when I use solve() function the command window goes in Waiting mode like
Waiting..........
My code is given below:
syms s T K D1 D2 D3 theta1 theta2 theta3 J1 J2 J3
eq1 = (s * D1 + K + J1 * s ^ 2)* theta1 - K * theta2 == T;
eq2 = -K * theta1 + (J2 * s ^ 2 + K + D2 * s) * theta2 - D2 * s * theta3 == 0;
eq3 = -D2 * s * theta2 + (D3 * s + J3 * s ^ 2 + D2 * s) * theta3 == 0;
S = solve(eq1, eq2, eq3)
but if I manually solve it by inverse method, it gives the answer instantly. Kindly help to solve this bug.
I'm trying to implement linear regression with only one feature using fminunc in Octave.
Here is my code.
x = load('/home/battousai/Downloads/ex2Data/ex2x.dat');
y = load('/home/battousai/Downloads/ex2Data/ex2y.dat');
m = length(y);
x = [ones(m , 1) , x];
theta = [0 , 0]';
X0 = [x , y , theta];
options = optimset('GradObj' , 'on' , 'MaxIter' , 1500);
[x , val] = fminunc(#computeCost , X0 , options)
And here is the cost function which returns the gradient as well as the value of the cost function.
function [J , gradient] = computeCost(x , y , theta)
m = length(y);
J = (0.5 / m) .* (x * theta - y )' * (x * theta - y );
gradient = (1/m) .* x' * (x * theta - y);
end
The length of the data set is 50, i.e., the dimensions are 50 x 1. I'm not getting the part that how should I pass X0 to the fminunc.
Updated Driver Code:
x = load('/home/battousai/Downloads/ex2Data/ex2x.dat');
y = load('/home/battousai/Downloads/ex2Data/ex2y.dat');
m = length(y);
x = [ones(m , 1) x];
theta_initial = [0 , 0];
options = optimset('Display','iter','GradObj','on' , 'MaxIter' , 100);
[X , Cost] = fminunc(#(t)(computeCost(x , y , theta)), theta_initial , options)
Updated Code for Cost function:
function [J , gradient] = computeCost(x , y , theta)
m = length(y);
J = (1/(2*m)) * ((x * theta) - y )' * ((x * theta) - y) ;
gradient = (1 / m) .* x' * ((x * theta) - y);
end
Now I'm getting values of theta to be [0,0] but when I used normal equation, values of theta turned out to be [0.750163 , 0.063881].
From the documentation for fminunc:
FCN should accept a vector (array) defining the unknown variables
and
X0 determines a starting guess.
Since your input is a cost function (i.e. it associates your choice of parameter vector with a cost), the input argument to your cost function, that needs to be optimised via fminunc is only theta, since x and y (i.e. your observations and your targets) are considered 'given' aspects of the problem and are not things you're trying to optimise. So you either declare x and y global and access them from your function like so:
function [J , gradient] = computeCost(theta_0)
global x; global y;
% ...
and then call fminunc as: fminunc (#computeCost, t_0, options)
or, keep your computeCost function as computeCost(x, y, theta), and change your fminunc call to something like this:
[x , val] = fminunc(# (t) computeCost(x, y, t) , t0 , options)
UPDATE Not sure what you were doing wrong. Here is the full code and an octave session running it. Seems fine.
%% in file myscript.m
x = load('ex2x.dat');
y = load('ex2y.dat');
m = length(y);
x = [ones(m , 1) , x];
theta_0 = [0 , 0]';
options = optimset('GradObj' , 'on' , 'MaxIter' , 1500);
[theta_opt, cost] = fminunc(# (t) computeCost(x,y,t) , theta_0 , options)
%% in file computeCost.m
function [J , gradient] = computeCost(x , y , theta)
m = length(y);
J = (0.5 / m) .* (x * theta - y )' * (x * theta - y );
gradient = (1/m) .* x' * (x * theta - y);
end
%% in the octave terminal:
>> myscript
theta_opt =
0.750163
0.063881
cost = 9.8707e-04
I am trying to get the following code to do a few more tricks:
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.answerLabel = Label(self, text="Output List:")
self.answerLabel.grid(row=2, column=1, sticky=W)
def psiFunction(self):
j = int(self.indexEntry.get())
valueList = list(self.listEntry.get())
x = map(int, valueList)
if x[0] != 0:
x.insert(0, 0)
rtn = []
for n2 in range(0, len(x) * j - 2):
n = n2 / j
r = n2 - n * j
rtn.append(j * x[n] + r * (x[n + 1] - x[n]))
self.answer = Label(self, text=rtn)
self.answer.grid(row=2, column=2, sticky=W)
if __name__ == "__main__":
root = Tk()
In particular, I am trying to get it to calculate len(x) * j - 1 terms, and to work for a variety of parameter values. If you try running it you should find that you get errors for larger parameter values. For example with a list 0,1,2,3,4 and a parameter j=3 we should run through the program and get 0123456789101112. However, I get an error that the last value is 'out of range' if I try to compute it.
I believe it's an issue with my function as defined. It seems the issue with parameters has something to do with the way it ties the parameter to the n value. Consider 0123. It works great if I use 2 as my parameter (called index in the function) but fails if I use 3.
EDIT:
def psi_j(x, j):
rtn = []
for n2 in range(0, len(x) * j - 2):
n = n2 / j
r = n2 - n * j
if r == 0:
rtn.append(j * x[n])
else:
rtn.append(j * x[n] + r * (x[n + 1] - x[n]))
print 'n2 =', n2, ': n =', n, ' r =' , r, ' rtn =', rtn
return rtn
For example if we have psi_j(x,2) with x = [0,1,2,3,4] we will be able to get [0,1,2,3,4,5,6,7,8,9,10,11] with an error on 12.
The idea though is that we should be able to calculate that last term. It is the 12th term of our output sequence, and 12 = 3*4+0 => 3*x[4] + 0*(x[n+1]-x[n]). Now, there is no 5th term to calculate so that's definitely an issue but we do not need that term since the second part of the equation is zero. Is there a way to write this into the equation?
If we think about the example data [0, 1, 2, 3] and a j of 3, the problem is that we're trying to get x[4]` in the last iteration.
len(x) * j - 2 for this data is 10
range(0, 10) is 0 through 9.
Manually processing our last iteration, allows us to resolve the code to this.
n = 3 # or 9 / 3
r = 0 # or 9 - 3 * 3
rtn.append(3 * x[3] + 0 * (x[3 + 1] - x[3]))
We have code trying to reach x[3 + 1], which doesn't exist when we only have indices 0 through 3.
To fix this, we could rewrite the code like this.
n = n2 / j
r = n2 - n * j
if r == 0:
rtn.append(j * x[n])
else:
rtn.append(j * x[n] + r * (x[n + 1] - x[n]))
If r is 0, then (x[n + 1] - x[n]) is irrelevant.
Please correct me if my math is wrong on that. I can't see a case where n >= len(x) and r != 0, but if that's possible, then my solution is invalid.
Without understanding that the purpose of the function is (is it a kind of filter? or smoothing function?), I prickled it out of the GUI suff and tested it alone:
def psiFunction(j, valueList):
x = map(int, valueList)
if x[0] != 0:
x.insert(0, 0)
rtn = []
for n2 in range(0, len(x) * j - 2):
n = n2 / j
r = n2 - n * j
print "n =", n, "max_n2 =", len(x) * j - 2, "n2 =", n2, "lx =", len(x), "r =", r
val = j * x[n] + r * (x[n + 1] - x[n])
rtn.append(val)
print j * x[n], r * (x[n + 1] - x[n]), val
return rtn
if __name__ == '__main__':
print psiFunction(3, [0, 1, 2, 3, 4])
Calling this module leads to some debugging output and, at the end, the mentionned error message.
Obviously, your x[n + 1] access fails, as n is 4 there, so n + 1 is 5, one too much for accessing the x array, which has length 5 and thus indexes from 0 to 4.
EDIT: Your psi_j() gives me the same behaviour.
Let me continue guessing: Whatever we want to do, we have to ensure that n + 1 stays below len(x). So maybe a
for n2 in range(0, (len(x) - 1) * j):
would be helpful. It only produces the numbers 0..11, but I think this is the only thing which can be expected out of it: the last items only can be
3*3 + 0*(4-3)
3*3 + 1*(4-3)
3*3 + 2*(4-3)
and stop. And this is achieved with the limit I mention here.