MATLAB: Multiplying a matrix by an unknown scalar (variable.) - matlab

I am trying to multiply a 3x2 matrix with an unknown scalar ( a number in terms of an unknown variable (t).
For instance 10t [<3x2 matrix>]. The variable t has no value and should always appear as a "t" instead of any numeric value. How do I get MATLAB to compute the result, while leaving the "t"'s as characters?

as David suggested use symbolic toolbox
type the following in matlab: syms t
however if you would describe what you are trying to do in more length, we might find out that you dont even need to use the symbolic toolbox. there might be other alternatives.

Related

Summing a series in 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.

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.

How can I create a symbolic integer for use with my Fourier transform?

I am computing a Fourier transformation in MATLAB, when computing coefficients C[0] and C[n*f0], I got pretty nasty result because MATLAB doesn't recognize my variable "n" as integer. I currently compute with "n" as a symbolic variable (syms n;). How to change symbolic n to symbolic integer n?
Looking at the MATLAB documenation, to add the assumption "n is integer" in R2008b or later, you have to write
evalin(symengine,'assume(n,Type::Integer)')
This answers your question, however, I'm not really sure it solves your problem.
When you do a Fourier transform, you are performing a heavy numeric operation on your data, consequently all variables involved in that need to have concrete values. Your n probably should be an integer, but not just by type, it should contain an actual number. If you declare it using syms, it will potentially not contain a number, so you be sure you really need the symbolic toolbox!
If you do, and n is the result of a calculation that yield one specific integer, you can convert it to normal numerical form using uint32(n) or similar, see the help on conversions, e.g.
Y = fft(X,uint32(n))
Update: The error message you give in the comment implies that your n is in fact not an integer... I doubt you will be able to use it with fft.

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.

How to go from a symbolic expression to a vector in MATLAB

I am working on a function that will generate polynomial interpolants for a given set of ordered pairs. You currently input the indexes of the node points in one vector, and the values of the function to be interpolated in a second vector. I then generate a symbolic expression for the Lagrange polynomial that interpolates that set of points. I would like to be able to go from this symbolic form to a vector form for comparison with test functions and such. That is, I have something that generates some polynomial P(x) in terms of some symbolic variable x. I would like to then sample this polynomial to a vector, and get values for the polynomial over (for example) linspace(-1,1,1000). If this is possible, how do I do it?
I guess I'll include the code that I have so far:
function l_poly = lpoly(x,f)
% Returns the polynomial interpolant as computed by lagrange's formula
syms a
n=size(x,2);
l_poly_vec = 1;
l_poly=0;
for k=1:n,
for l=1:n,
if (k ~= l)
l_poly_vec=l_poly_vec*(a-x(l))/(x(k)-x(l));
end
end
l_poly=l_poly+f(k)*l_poly_vec;
l_poly_vec = 1;
end
I plan on adding a third (or possibly fourth) input depending on how I can solve this issue. I'm guessing I would just need the length of the vector I want to sample to and the endpoints.
If I understand you correctly, you've constructed a Lagrange interpolating polynomial using the symbolic toolbox and now wish to evaluate it over a vector of values. One way to do this is to use the function sym2poly to extract the coefficients of the symbolic polynomial, and then use polyval to evaluate it. Alternatively, you could use matlabFunction to convert your symbolic expression into a regular Matlab function; or use subs to substitute in a numeric value for 'x'.
However, you would probably be better off avoiding the symbolic toolbox altogether and directly constructing the coefficients of the Lagrange interpolating polynomial, or, better yet, use a different interpolation scheme altogether. The function interp1 might be a good place to start.