Summing a series in matlab - matlab

I'm trying to write a generic function for finding the cosine of a value inputted into the function. The formula for cosine that I'm using is:
n
cosx = sum((-1)^n*x^(2n)/(2n)!)
n=1
I've looked at the matlab documentation and this page implies that the "sum" function should be able to do it so I tried to test it by entering:
sum(x^n, n=1..3)
but it just gives me "Error: The expression to the left of the equals sign is not a valid target for an assignment".
Is summing an infinite series something that matlab is able to do by default or do I have to simulate it using a function and loops?

Well if you want to approximate it to a finite number of terms you can do it in Matlab without toolboxes or loops:
sumCos = #(x, n)(sum(((-1).^(0:n)).*(x.^(2*(0:n)))./(factorial(2*(0:n)))));
and then use it like this
sumCos(pi, 30)
The first parameter is the angle, the second is the number of terms you want to take the series to (i.e. effects the precision). This is a numerical solution which I think is really what you're after.
btw I took the liberty of correcting your initial sum, surely n must start from 0 if you are trying to approximate cos
If you want to understand my formula (which surely you do) then you need to read up on some essential Matlab basics namely the colon operator and then the concept of using . to perform element-wise operations.

In MATLAB itself, no, you cannot solve an infinite sum. You would have to estimate it as you suggested. The page you were looking at is part of the Symbolic Math toolbox, which is an add-on to MATLAB. In particular, you were looking at MuPAD, which is rather similar to Mathematica. It is a symbolic math workspace, whereas MATLAB is more of a numeric math workspace. If you own the Symbolic Math toolbox, you can either use MuPAD as you tried to above, or you can use the symsum function from within MATLAB itself to carry out sums of series.

Related

For loop equation into Octave / Matlab code

I'm using octave 3.8.1 which works like matlab.
I have an array of thousands of values I've only included three groupings as an example below:
(amp1=0.2; freq1=3; phase1=1; is an example of one grouping)
t=0;
amp1=0.2; freq1=3; phase1=1; %1st grouping
amp2=1.4; freq2=2; phase2=1.7; %2nd grouping
amp3=0.8; freq3=5; phase3=1.5; %3rd grouping
The Octave / Matlab code below solves for Y so I can plug it back into the equation to check values along with calculating values not located in the array.
clear all
t=0;
Y=0;
a1=[.2,3,1;1.4,2,1.7;.8,5,1.5]
for kk=1:1:length(a1)
Y=Y+a1(kk,1)*cos ((a1(kk,2))*t+a1(kk,3))
kk
end
Y
PS: I'm not trying to solve for Y since it's already solved for I'm trying to solve for Phase
The formulas located below are used to calculate Phase but I'm not sure how to put it into a for loop that will work in an array of n groupings:
How would I write the equation / for loop for finding the phase if I want to find freq=2.5 and amp=.23 and the phase is unknown I've looked online and it may require writing non linear equations which I'm not sure how to convert what I'm trying to do into such an equation.
phase1_test=acos(Y/amp1-amp3*cos(2*freq3*pi*t+phase3)/amp1-amp2*cos(2*freq2*pi*t+phase2)/amp1)-2*freq1*pi*t
phase2_test=acos(Y/amp2-amp3*cos(2*freq3*pi*t+phase3)/amp2-amp1*cos(2*freq1*pi*t+phase1)/amp2)-2*freq2*pi*t
phase3_test=acos(Y/amp3-amp2*cos(2*freq2*pi*t+phase2)/amp3-amp1*cos(2*freq1*pi*t+phase1)/amp3)-2*freq2*pi*t
Image of formula below:
I would like to do a check / calculate phases if given a freq and amp values.
I know I have to do a for loop but how do I convert the phase equation into a for loop so it will work on n groupings in an array and calculate different values not found in the array?
Basically I would be given an array of n groupings and freq=2.5 and amp=.23 and use the formula to calculate phase. Note: freq will not always be in the array hence why I'm trying to calculate the phase using a formula.
Ok, I think I finally understand your question:
you are trying to find a set of phase1, phase2,..., phaseN, such that equations like the ones you describe are satisfied
You know how to find y, and you supply values for freq and amp.
In Matlab, such a problem would be solved using, for example fsolve, but let's look at your problem step by step.
For simplicity, let me re-write your equations for phase1, phase2, and phase3. For example, your first equation, the one for phase1, would read
amp1*cos(phase1 + 2 freq1 pi t) + amp2*cos(2 freq2 pi t + phase2) + amp3*cos(2 freq3 pi t + phase3) - y = 0
Note that ampX (X is a placeholder for 1, 2, 3) are given, pi is a constant, t is given via Y (I think), freqX are given.
Hence, you are, in fact, dealing with a non-linear vector equation of the form
F(phase) = 0
where F is a multi-dimensional (vector) function taking a multi-dimensional (vector) input variable phase (comprised of phase1, phase2,..., phaseN). And you are looking for the set of phaseX, where all of the components of your vector function F are zero. N.B. F is a shorthand for your functions. Therefore, the first component of F, called f1, for example, is
f1 = amp1*cos(phase1+...) + amp2*cos(phase2+...) + amp3*cos(phase3+...) - y = 0.
Hence, f1 is a one-dimensional function of phase1, phase2, and phase3.
The technical term for what you are trying to do is find a zero of a non-linear vector function, or find a solution of a non-linear vector function. In Matlab, there are different approaches.
For a one-dimensional function, you can use fzero, which is explained at http://www.mathworks.com/help/matlab/ref/fzero.html?refresh=true
For a multi-dimensional (vector) function as yours, I would look into using fsolve, which is part of Matlab's optimization toolbox (which means I don't know how to do this in Octave). The function fsolve is explained at http://www.mathworks.com/help/optim/ug/fsolve.html
If you know an approximate solution for your phases, you may also look into iterative, local methods.
In particular, I would recommend you look into the Newton's Method, which allows you to find a solution to your system of equations F. Wikipedia has a good explanation of Newton's Method at https://en.wikipedia.org/wiki/Newton%27s_method . Newton iterations are very simple to implement and you should find a lot of resources online. You will have to compute the derivative of your function F with respect to each of your variables phaseX, which is very simple to compute since you're only dealing with cos() functions. For starters, have a look at the one-dimensional Newton iteration method in Matlab at http://www.math.colostate.edu/~gerhard/classes/331/lab/newton.html .
Finally, if you want to dig deeper, I found a textbook on this topic from the society for industrial and applied math: https://www.siam.org/books/textbooks/fr16_book.pdf .
As you can see, this is a very large field; Newton's method should be able to help you out, though.
Good luck!

Differentiate function without Symbolic Math Toolbox

If I want to differentiate a function, I would do the following:
syms x
f(x) = sin(x^2);
df = diff(f)
,but that requires the use of the Symbolic Math Toolbox (for the syms function).
Is there a workaround (an alternative) to this method without the use of the Symbolic Toolbox?
If you have a numerical vector and you'd like to differentiate it, then the gradient function is your friend.
If you want to differentiate a symbolic expressing then the Symbolic Math Toolbox is the only way to go within Matlab. If pen&paper together with wolframalpha.com does not serve you, there is no way around to buy the toolbox or use alternatives like Wolframs Mathematica, Maple, Maxima, Sympy, Sage etc..
https://www.mathworks.com/matlabcentral/fileexchange/59438-symbolic-derivatives
In the above link, you will find a function that requires string 'sin(x^2)' as input and gives you something like 'cos(x^2)*2*x' (i.e. also a string). You may then use standard Matlab's eval() to evaluate the derivative numerically at any x point.

Using the Pochhammer Symbol in Matlab

I've tried to use a script that evaluates the Pochhammer symbol (rising factorial) in Matlab, but it fails to evaluate pochhammer(x,n) whenever x is a negative number even though the expression is valid when x is negative (Wolfram Alpha and Mathematica give answers for Pochhammer(-3,2)).
Can anyone help me get pochhammer working in Matlab for negative arguments?
I assume that you're referring to this Pochhammer function. Note that pochhammer (not capitalized) is part of MuPAD, which is a separate environment available with Matlab's Symbolic Math Toolbox. You can access MuPAD by typing mupad in the Matlab command window.
If, however, like a normal Matlab user, you wish to use the pochhammer function from Matlab itself and program with it, you cannot run it from the regular command window or Editor in the normal fashion, as you discovered. Instead, you must use
evalin(symengine,'pochhammer(-3,2)')
or the more flexible
feval(symengine,'pochhammer',-3,2)
See more here. These both return symbolic numbers as results and only work for scalar inputs. If you require double-precision output and have vector inputs (only works for the the second one, n) use
mfun('pochhammer',-3,-3:3)
This is equivalent to using MuPAD's map function, so you could also write:
feval(symengine,'map',sym(-3:3),'n->pochhammer(-3,n)')
However, if you're not working with symbolic math at all, there may be no reason to use this function instead of a fully double-precision solution. The Pochhammer symbol is defined simply as the ratio of two gamma functions and can be implemented efficiently as (x and n must be the same dimensions or scalar – additionally, neither x nor x-n can be an integer less than or equal to zero, where the gamma function is singular):
poch = #(x,n)gamma(x+n)./gamma(x);
If n and x are integers you should use round to ensure that the output is exactly integer. The only pitfall is that for sufficiently large values of x and/or n this naïve implementation will overflow to Inf (or NaN). In these cases you'll need to do something else such as use the symbolic version (which may or may not return Inf when cast back to double). For integer values of n (and scalar n>=0), something like the following can be used
poch = #(x,n)prod(bsxfun(#plus,x(:),0:n-1),2);
Note that even for integers this can be up 20 times slower than the gamma version.
The numerical command pochhammer for Matlab (not MuPAD) was introduced in matlab version R2014b.

Minimizing error of a formula in MATLAB (Least squares?)

I'm not too familiar with MATLAB or computational mathematics so I was wondering how I might solve an equation involving the sum of squares, where each term involves two vectors- one known and one unknown. This formula is supposed to represent the error and I need to minimize the error. I think I'm supposed to use least squares but I don't know too much about it and I'm wondering what function is best for doing that and what arguments would represent my equation. My teacher also mentioned something about taking derivatives and he formed a matrix using derivatives which confused me even more- am I required to take derivatives?
The problem that you must be trying to solve is
Min u'u = min \sum_i u_i^2, u=y-Xbeta, where u is the error, y is the vector of dependent variables you are trying to explain, X is a matrix of independent variables and beta is the vector you want to estimate.
Since sum u_i^2 is diferentiable (and convex), you can evaluate the minimal of this expression calculating its derivative and making it equal to zero.
If you do that, you find that beta=inv(X'X)X'y. This maybe calculated using the matlab function regress http://www.mathworks.com/help/stats/regress.html or writing this formula in Matlab. However, you should be careful how to evaluate the inverse (X'X) see Most efficient matrix inversion in MATLAB

MuPad: Cannot work with symbolic expansion when handling matricial expressions

I am working MuPad in order to have a symbolic tool to find solution for an equation. But I am working with matrices.
Consider this:
blck := A -> matrix([
[A[1..linalg::matdim(A)[1]/2,1..linalg::matdim(a)[2]/2],
A[1..linalg::matdim(A)[1]/2,linalg::matdim(A)[2]/2+1..linalg::matdim(A)[2]]],
[A[linalg::matdim(A)[1]/2+1..linalg::matdim(A)[1],1..linalg::matdim(A)[2]/2],
A[linalg::matdim(A)[1]/2+1..linalg::matdim(A)[1],linalg::matdim(A)[2]/2+1..linalg::matdim(A)[2]]]
])
This function enables me to have a block representation of a matrix and it works. Now consider this function
myfun := A -> matrix([[blck(A)[1,1]*blck(A)[2,2]*blck(A)[2,1],blck(A)[1,1]],
[blck(A)[1,1],blck(A)[1,1]]])
This will manipulate a little a matrix and returns matrix whose components are combined somehow. The problem is that, considering that I cannot tell MuPad that matrix A and its components are matrices and not reals, it happens that MuPad will show me matrix products in different order
For example. Consider
myfun(matrix([[A11,A12],[A21,A22]]))
The first component of the returned matrix, element (1,1), is A11*A21*A22 which is incorrect being A11,A12,A21,A22 matrices!
How can i tell MuPad that A11,A12,A21 and A22 are matrices so that MuPad will expand products correctly?
You can have matrices in matrices in MuPAD, as long as you explicitly put them in there. Just telling the system to treat A1*A2 as non-commutative is more difficult and not well supported. You could go full-blown, create your own datatype and implement arithmetic accordingly, but that's not necessarily easy if you still want simplifications to happen.