Matrix dimension error while calling mldivide in MATLAB - 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.

Related

What type of operation should you use on single expressions containing vectors and numbers in Matlab?

I am trying to produce a contour plot of the following equation in Matlab.
theta=[(k+0.5)^2+t^2]^(-1/2)-[(k-0.5)^2+t^2]^(-1/2).
This is how I initially expressed it.
k=linspace(-1,1,20);
t=linspace(-0.5,0.5,20);
[K,T]=meshgrid(k,t);
Z=((K+0.5)^2+T.^2)^-0.5 -((K-0.5)^2+T.^2)^-0.5;
contour(K,T,Z, 'ShowText', 'on')
I'm getting the error message 'Input arguments for contour must be real.' so assuming I have expressed the equation wrong in the 4th line. I'm confused as to what type of operation I should use for expressions such as (K+0.5)^2+T.^2, where there are both vectors and numbers. How should I express it in Matlab syntax?
Apologies if the question is really basic. Absolute beginner.
The immediate error is because Z contains complex values (has non-zero imaginary components).
The real issue though is that you have used the matrix power (^) rather than an element-wise power (.^) in some places in your definition of Z.
Your expression to compute Z should actually be:
Z = ((K + 0.5).^2 + T.^2).^-0.5 - ((K - 0.5).^2 + T.^2).^-0.5;

MATLAB: pdepe boundary function

Why did I get an error like ''Subscript indices must either be real positive integers or logicals. Error in bcfcn (line 7) qr = Ds*J(t,1)'' when I used pdepe matlab solver to solve diffusion equation on spherical coordinate. The Ds is just an constant but J is actually a vector with respect to time which has both very large positive and negative integers. I cannot change these value to all positive since it is a boundary condition given.
Is that because I need to change the J vector to some function with respect to time?? Actually I have tried to change all J to positive to figure out how does it work, but it doesn't work either.
Thank you very much!
Lu

Triple integral using trapz over a part of a rectangular box

I am trying to evaluate a triple integral using the 'trapz' command in MATLAB. My integrand is function of gamma1,gamma2,s... I want to evaluate the integral numerically and not symbolically.
syms gamma1; syms gamma2; syms s
f=gamma1*gamma2*exp(-s*10);
x= -20:0.3:20;
y=linspace(0.1,100000,length(x));
z=linspace(0.1,100000,length(x));
[s,gamma1,gamma2] = ndgrid(x,y,z);
mat=eval(f).* (gamma2>gamma1); %MY QUESTION IS HERE
out = trapz(x,trapz(y,trapz(z,mat,3),2),1);
My question is I have a condition on my integrand, it should be evaluated ONLY when gamma2 >gamma1. Is my code correct above i.e is the way I add the logical statement correct?
Yes, the logic is correct: mat will have zeros where the condition gamma2>gamma1 fails.
You can test correctness yourself by using an example where you know the answer already. For instance, integration of f=gamma1*gamma2*s within [0,2] in each variable gives 8 (with paper and pencil), and if the condition gamma2>gamma1 is added, the result is halved (by symmetry), so it becomes 4. And indeed, your code returns approximately 4 for this function.
As an aside: you may want to reconsider the desirability of using the same number of sample points in every dimension, given the disparity of sizes (40 by 100000 by 100000).

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

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.