How to get only the positive solution to a quadratic equation using the MATLAB Symbolic Toolbox? - matlab

I want to solve this equation in Matlab.
e=2;
while (e<30)
syms v;
solve('(v-e) = -(0.5*0.2*1.276*v^2*0.3)');
e=e+1;
end
When I write for example "solve('(v-10) = -(0.5*0.2*1.276*v^2*0.3)');" it works. But I need variable "e" in this equation.
In some cases, this equation has 2 solutions (negative and positive), but I need only positive solutions. What is the correct syntax? Thank you.

To add e to your equation you can concact it as a number to your equation: ['equation part one', num2str(e), 'end of your equation'].
To only have the positive solution, you can add a condition to your equation ( v>=0 ).
Here is an example of a complete solution to your problem:
ans = zeros(1,size(2:29,2));
i = 0;
syms v;
for e = 2:29
i = i+1;
ans(i) = solve(['(v-',num2str(e),') = -(0.5*0.2*1.276*v^2*0.3) and v>=0']);
end

There's no need to use strings unless you're using a really old version of Matlab. This is the modern and preferred way of using solve:
syms v positive;
e = 2:29;
s = zeros(length(e),1);
for i=1:length(e)
s(i) = double(solve(v-e(i)==-0.5*0.2*1.276*v^2*0.3,v));
end
However, since this is just a polynomial you can use the roots function:
e = 2:29;
s = zeros(length(e),1);
for i=1:length(e)
r = roots([0.5*0.2*1.276*0.3 1 -e(i)]);
s(i) = r(r>=0);
end

Related

MATLAB want to convert explicit euler algorithm to implicit euler algorithm for SYSTEM of 1st order ODEs

Before anything, I can't use ANY built-in ODE solvers for this. I coded this system of ODEs with explicit euler's method but I need to instead rewrite it with implicit euler's. If I just switch the "i" to "i+1" (ex "y(1,i)" to "y(1,i+1)") then the answer comes out obscenely wrong.
A_init= 4;
B_init= 1.1;
C_init= 4;
y0 = [A_init; B_init; C_init];
h = 20/100;
n = 100;
t0 = 0;
tf = 20;
t = linspace(t0,tf,n);
y = zeros(numel(y0) , n);
y(:, 1) = y0(:);
dAdt= #(a,b) 7.27*(b-a*b+ a-(8.375*10^-5)*a^3);
dBdt= #(b,a,c)(-b-a*b+c)/77.27;
dCdt= #(c,a) 0.4*(a-c);
for i = 1:n-1
y(1,i+1) = y(1,i) +h*feval(dAdt,y(1,i),y(2,i));
y(3,i+1) = y(3,i) +h*feval(dCdt,y(3,i),y(1,i));
y(2,i+1) = y(2,i) +h*feval(dBdt,y(2,i),y(1,i),y(3,i));
end
Your idea is correct, but remember that if you change the i on the right-hand side to i+1, you will have y(1,i+1), y(2,i+1), y(3,i+1) appearing on both sides of the equation. This means that you actually have to solve for y(1,i+1), y(2,i+1) and y(3,i+1) at each step. Since your three equations are coupled, you have to solve a nonlinear system of equations at each time-step, using fsolve or fzero.
Read the answer to this question, which shows how to do this for the single equation case.

Solving for Fisher Kolmagorov Partial Differential Equation

I have been trying to solve the non dimensional Fisher Kolmagorov equation in Matlab. I am getting a graph which doesn't look at all like it should. Also, I'm getting the equation independent of value of s (the source term in the pdepe solver). No matter what value of s I put in the graph remains the same.
function FK
m = 0;
x = linspace(0,1,100);
t = linspace(0,1,100);
u = pdepe(m,#FKpde,#FKic,#FKbc,x,t);
[X,T] = meshgrid(x,t);
%ANALYTICAL SOLUTION
% a=(sqrt(2))-1;
% q=2;
% s=2/q;
% b= q /((2*(q+2))^0.5);
% c= (q+4)/((2*(q+2))^0.5);
% zeta= X-c*T;
%y = 1/((1+(a*(exp(b*zeta))))^s);
%r=(y(:,:)-u(:,:))./y(:,:); % relative error in numerical and analytical value
figure;
plot(x,u(10,:),'o',x,u(40,:),'o',x,u(60,:),'o',x,u(end,:),'o')
title('Numerical Solutions at different times');
legend('tn=1','tn=5','tn=30','tn=10','ta=20','ta=600','ta=800','ta=1000',0);
xlabel('Distance x');
ylabel('u(x,t)');
% --------------------------------------------------------------------------
function [c,f,s] = FKpde(x,t,u,DuDx)
c = 1;
f = DuDx;
s =u*(1-u);
% --------------------------------------------------------------------------
function u0 = FKic(x)
u0 = 10^(-4);
% --------------------------------------------------------------------------
function [pl,ql,pr,qr] = FKbc(xl,ul,xr,ur,t)
pl = ul-1;
ql = 0;
pr = ur;
qr = 0;
Should maybe be a comment, but putting it as an answer for better formatting. Your analytic solution, which I assume you're using to compare with the numerical answer to say that the graph does not look as it should, does not appear to respect the initial conditions or boundary conditions you are feeding pdepe, so I'd start there if trying to figure out why u does not look like y
The initial and boundary conditions you are setting are:
u(0, t) = 1
u(1, t) = 0
u(x, 0) = 1e-4
Setting aside that the boundary and initial conditions are in conflict, the analytic solution you suggest in the code has
u(0, t) = 1/((1+exp(-b*ct)))
u(1, t) = 1/((1+exp(b*(1-ct)))
u(x, 0) = 1/((1+exp(b*x))
So it seems to me the numerical and analytic solutions should be expected to be different, and the differences you observe are probably due to the IC/BC setup. I suspect that pdepe is probably solving the equation you are giving it.
On increasing the length scale and time scale, I get the answers I want. The problem was to solve for different times, and see the wave propogate. For small lenghts, I could only see part of that wave.

Plotting the Taylor polynomial of the sine function

I'm trying to code Taylor summation for a function in Matlab, I actually evaluate McLaurin making x=0, named a in this code after this notation:
This is the code I've tried out so far:
>> a = -100;
b = 100;
n = 20;
vectorx = linspace(a,b,50);
vectory = [];
sumterms = [];
syms x y a;
y = sin(a);
for i = 1:n
t = (diff(y,i-1) / factorial(i-1)) * (x-0)^(i-1);
sumterms = [sumterms;t];
end;
sumterms
for j = 1:length(vectorx)
x_i = vectorx(j);
aux = 0;
for k = 1:length(sumterms)
sumterm = sumterms(k);
aux = aux + subs(sumterm, [a,x], [0,x_i]);
end
vectory = [vectory;aux];
end
length(vectory)
length(vectorx)
plot (vectorx, vectory)
But I'm not getting correct results
I've step over each sentence and I can't really see what's wrong about it.
This is my plot result for sin(x):
And this is plot for exponential(x)
Sumterms results for each appear in the image capture, and they seem to be ok, however I think error is in evaluation.
Your code works correctly and plots the correct Taylor polynomial. Your mistake is that you are expecting a 20th degree Taylor polynomial to approximate the sine function on the interval [-100,100]. This is much too optimistic. It gives a decent approximation on [-5,5] and that's about it. Here is the output of your code with a=-9, b=9, where the problems already appear:
Indeed, x^n/n! is about (e*x/n)^n, using a rough version of Stirling's formula. So you need |x| < n/e to avoid a catastrophically large error term, and an even smaller interval (like |x| < n/3 ) to have a good approximation. With n=20, n/3 is 6.66...

Formulating a summation objective function to minimize for fmincon in MatLab

I have a summation objective function (non-linear portfolio optimization) which looks like:
minimize w(i)*w(j)*cv(i,j) for i = 1 to 10 and j = 1 to 10
w is the decision vector
cv is a known 10 by 10 matrix
I have the formulation done for the constraints (a separate .m file for the project constraints) and for the execution of the fmincon (a separate .m file for the lower/upper bounds, initial value, and calling fmincon with the arguments).
I just can't figure out how to do the objective function. I'm used to linear programming in GLPK rather than matlab so I'm not doing so good.
I'm currently got:
ObjectiveFunction.m
function f = obj(w)
cv = [all the constants are in here]
i = 1;
j = 1;
n = 10;
var = 0;
while i <= n
while j<=n
var = var + abs(w(i)*w(j)*cv(i, j));
j = j + 1;
end
i = i + 1;
end
f = var
...but this isn't working.
Any help would be appreciated! Thanks in advance :)
So this is from a class I took a few years ago, but it addresses a very similar problem to your own with respect to use of fminsearch to optimize some values. The problem is essentially that you have a t, y, and you want a continuous exponential function to represent t, y in terms of c1*t.*exp(c2*t). The textbook I lifted the values from is called Numerical Analysis by Timothy Sauer. Unfortunately, I don’t remember the exact problem or chapter, but it’s in there somewhere.
c1 and c2 are found recursively by fminsearch minimizing a residual y - ((c1) * t .* exp((c2) * t)). Try copying and running my code below to get a feel for things:
%% Main code
clear all;
t = [1,2,3,4,5,6,7,8];
y = [8,12.3,15.5,16.8,17.1,15.8,15.2,14];
lambda0=[1 -.5];
lambda=fminunc(#expdecayfun,lambda0, ...
optimset('LargeScale','off','Display','iter','TolX',1.e-6),t,y);
c1=lambda(1);
c2=lambda(2);
fprintf('Using the BFGS method through fminunc, c1 = %e\n',c1);
fprintf('and c2 = %e. Since these values match textbook values for\n', c2);
fprintf('c1 and c2, I will stop here.\n');
%% Index of functions:
% expdecayfun
function res=expdecayfun(lambda,t,y) c1=lambda(1);
c2=lambda(2);
r=y-((c1)*t.*exp((c2)*t));
res=norm(r);
Hope this helps!

MATLAB and function

I want to calculate the function y(t) from the equation:
y(t) = -3t^2+5, t>=0
y(t) = 3t^2+5, t<0
for -9 <= t <= with the step-size 0.5
And I want to plot it by using MATLAB. I approach this question in two ways:
First
t=0:0.5:9
y=-3*t^2+5
t1=-0.00000000001:0.5:-9
y1=3*t^2+5
plot(t,y,t1,y1)
Second by using loop
t=-9:0.5:9
if(t>=0)
y=-3*(t.^2)+5
else
y=3.*(t.^2)+5
end
plot(t,y)
My problem is the two ways above seem not to give the same answer... Which one is the correct answer?
You can use the sign function to do this particular example a little easier:
t = -9:0.5:9;
y = -sign(t)*3.*t.^2 + 5;
plot(t,y);
In your first attempt, your t1 definition should be:
t1 = 0:-0.5:-9;
Note the minus sign on the increment.
Using a "loop" you seem to have left out the actual loop part. Try something like
t = -9:0.5:9;
for idx = 1:length(t)
if t(idx) <= 0
y(idx) = -3*(t(idx).^2)+5
etc.
Here's a more idiomatic solution that avoids SIGN for cases where that's not the only difference.
t = -9:0.5:9
y = -3*t.^2+5
y(t<0) = 3*t(t<0).^2+5
plot(t, y)