Plotting the sum of series - matlab

I use this code and i don't know what it needs to work for my problem:
syms x k t
for t=0:10
num=((-1)^k)/k
t1=sin(8*3.1415*k*t)
S1=symsum((num*t1),k,1,2);
x=0.5-((1/3.1415)*S1);
end
Plot(x)
On the x axis I show time and on the y axis I show the function over four periods.
When I try to run the code I get the following error:
Undefined function 'symsum' for input arguments of type 'double'.
Maybe I can't use symsum with my argument type, but is there another function I can use? Sum also didn't work:
Error using sum Dimension argument must be a positive integer scalar within indexing range.

Since you want to plot x(t), you need to use plot(t,x) where t and x are vectors.
Instead of using for t=0:10, just let t=0:10 and calculate the corresponding x.
Also, the symbolic variable is just k.
syms k
t=0:10;
num=((-1)^k)/k;
t1=sin(8*3.1415*k*t);
S1=symsum((num*t1),k,1,2);
x=0.5-((1/3.1415)*S1);
plot(t,x)
It is noted that if you let t=0:10, then the sin(8*k*pi*t) will always be 0 since t is a vector of the integer from 0 to 10. The result of x(t) will be 5:
Output when t=0:10:
As you can see, the value of x(t) is very close to each other. Theoretically, they should all be 5. But there is some numerical approximation which leads to the small error.
You probably want non-integer t. Here is a output when t=0:0.1:10

Related

Numerical gradient of a Matlab function evaluated at a certain point

I have a Matlab function G(x,y,z). At each given (x,y,z), G(x,y,z) is a scalar. x=(x1,x2,...,xK) is a Kx1 vector.
Let us fix y,z at some given values. I would like your help to understand how to compute the derivative of G with respect to xk evaluated at a certain x.
For example, suppose K=3
function f= G(x1,x2,x3,y,z)
f=3*x1*sin(z)*cos(y)+3*x2*sin(z)*cos(y)+3*x3*sin(z)*cos(y);
end
How do I compute the derivative of G(x1,x2,x3,4,3) wrto x2 and then evaluate it at x=(1,2,6)?
You're looking for the partial derivative of dG/dx2
So the first thing would be getting rid of your fixed variables
G2 = #(x2) G(1,x2,6,4,3);
The numerical derivatives are finite differences, you need to choose an step h for your finite difference, and an appropriate method
The simplest one is
(G2(x2+h)-G2(x2))/h
You can make h as small as your numeric precision allows you to. At the limit h -> 0 the finite difference is the partial derivative

How do I get the values of y and y' for specific values of t from ode45 in Matlab?

I have to solve a second-degree differential equation and I specifically need the value of the first derivative of y at the final time point. My code is the following:
[T Y]=ode45(#(t y)vdp4(t,y,0.3),[0 1],[0.3/4,((3*0.3)^0.5)/2]);
I know the output will contain the values at which ode45 evaluated the function. To get the y values at specific time value at have it has been advised to give more than two time points in the MATLAB documentation. I did that too.
tspan=[0:0.01:1]
[T Y]=ode45(#(t y)vdp4(t,y,0.3),tspan,[0.3/4,((3*0.3)^0.5)/2]);
The T vector still does not have all the values from 0 to 1 (The last value is 0.39). This happens especially after multiple executions of ode45 function. I found something else in the MATLAB documentation: using "sol" structure to deval the values for specific t values. Is that the right way to go?
For reference, my differential equation is in the following function.
function dy = vdp4(t,y,k)
dy = zeros(2,1); % a column vector
dy(1)=y(2);
dy(2)=(y(2)^2-2*t*y(2)+2*y(1))/k+2;
end
Edit: I provided the parameter value. It should now be executable.
Try to plot your solution, you will find the answer

zeros of a vector-valued function

Is there any function in MATLAB that can find the zeros of a vector-valued function? The commonly used function fzero is just for scalar functions and also cannot find the zeros of any scalar function such as f(x)=x^2.
Matlab's optimization toolbox has the fsolve method that states it is capable of:
Solves a problem specified by F(x) = 0 for x, where F(x) is a function that returns a vector value. x is a vector or a matrix.
Otherwise, finding zeroes of a generic vector valued function can be done by attempting to minimize the norm of the vectorial output. Lets assume your function F(x) outputs an Nx1 vector. You could attempt to find the zero by doing the following:
y = fminunc(#(x) sum(F(x).^2));
or
y = fminsearch(#(x) sum(F(x).^2));
You would then have to check if the returned y is "sufficiently close" to zero.
One last comment, the fzero function's algorithm determines the existence of roots by checking for sign changes. The [docs] explicitly say that
x = fzero(fun,x0) tries to find a point x where fun(x) = 0. This solution is where fun(x) changes sign. fzero cannot find a root of a function such as x^2.
In fact, in older versions of matlab (R2012b) the fzero's doc had a section with its limitations that said
The fzero command finds a point where the function changes sign. If the function is continuous, this is also a point where the function has a value near zero. If the function is not continuous, fzero may return values that are discontinuous points instead of zeros. For example, fzero(#tan,1) returns 1.5708, a discontinuous point in tan.
Furthermore, the fzero command defines a zero as a point where the function crosses the x-axis. Points where the function touches, but does not cross, the x-axis are not valid zeros. For example, y = x.^2 is a parabola that touches the x-axis at 0. Because the function never crosses the x-axis, however, no zero is found. For functions with no valid zeros, fzero executes until Inf, NaN, or a complex value is detected.
Maybe I misunderstand something in your question, but you can try this solution:
y = #(x) x^2;
fminbnd(y, -100, 100)
ans = -3.5527e-15
And maybe you can try solve:
syms x y
y = #(x) x^2;
solve( y==0, x);
Can't check it right now, I will edit this solution a little bit later.

Plotting an equation with two input variables using meshgrid() in MATLAB - matrix incompatibility

I am trying to plot a 3D graph of an equation that has two input variables: time, t and spring constant, K in order to investigate the effect of K on the output. I have looked in to how to plot a function with two input variables using meshgrid() and converting the two inputs into compatible matrices.
For multiplying one of those inputs, say 't'. The multiplication sign needs to be preceded by '.' e.g y = t.*C (where C is some constant). For two inputs it is the same; e.g y = t.*C + K.^2.
However I cannot find how to do that for division, if the variable is in the numerator I assume you can simply write the expression as say: t*1/C. However how do you write it when the variable is in the denominator as in 'C/t'. I have tried placing '.' after 't' in the denominator however I get an error:
Error using /
Matrix dimensions must agree.
Also do I need to put the '.' after the variable in an addition?
Apologies if all this seems vague. I can put in the actual equation however it extremely long and it works when only t is a variable and K is a constant so the equation itself is sound.
The operations that have to be preceded with a . to apply element-wise are:
Multiplication: .*
Division: ./
Power: .^
Thus, if A, B, and C are arrays, you write
y = (A.*B./C).^2

Matrix dimension error while calling mldivide in MATLAB

I am getting this error while running my code:
Error using ==> mldivide Matrix dimensions must agree.
Here is my code :
%make the plots of phase and group velocity vs discreteness of the grid
c=1;
a=input('Please enter the ratio cdt/dx : ')
figure(1)
R=2:40;
plot(R,phase_vel(R,a)/c)
xlabel('R=l/dx')
ylabel('u_phase/c')
%figure(2)
%plot(group_vel(R,a),R,0,40)
%xlabel('R=l/dx')
%ylabel('u_group/c')
and here are my functions :
function phase_velocity = phase_vel(R,a)
%numerical phase velocity of the discrete wave
c=1;
phase_velocity=(2*pi*c)/(R*knum(R,a));
end
function group_velocity =group_vel(R,a )
%numerical group velocity of the discrete wave
c=1;
group_velocity=(a*sin(knum(R,a)))/(sin(2*pi*a/R))
end
function knumber = knum(R,a)
%This is the k wave number
knumber=acos((1/a)^2*(cos(2*pi*a/R)-1)+1);
end
How can I resolve this error?
EDIT: I used . operator in every equation and i changed the limits of R=4:40
If your goal is to apply your formulas to each individual value in the vector R then you should be performing all of your computations using the element-wise arithmetic operators .*, ./, and .^ instead of the matrix operators *, /, and ^.
Your error is probably occurring in the first call to your function knum, specifically when you try to compute 2*pi*a/R. Since 2*pi*a is a single scalar value, you get an error when trying to perform matrix right division / using the row vector R. The really weird thing is the error message:
??? Error using ==> mldivide
Matrix dimensions must agree.
which implies you are using the matrix left division operator \, which you clearly aren't. I tested this in MATLAB R2010b and I get the same incorrect function name appearing in my message. I think this may just be a typo in the error message, and I've dropped a note to the MATLAB folks to take a look at it and clear it up.
I don't have the Symbolic Math Toolbox, but your problem seems to be that you are using plot, a function which can deal with arrays of numbers, and feeding it the result of a symbolic calculation. Have a look at the Matlab Help, where the Topic Creating Plots of Symbolic Functions suggests using ezplot(). Alternatively you need to evaluate your symbolic expression for certain input values to create an array of numbers that plot can deal with - but you can't use double() for that since it wouldn't know what numbers to plug into your variables.