I can't multiple numbers in matlab - matlab

I need to find rp for each x but I'm having a hard time because matlab gives me this error
Error in enee_408e_hw2_pb1 (line 6)
rp=(z2*cos(t2)-z1*cos(x))/(z2*cos(t2)+z1*cos(x))
here is my code
x=0:.01:pi/2;
n2=1.7;
t2=asin(sin(x)/n2);
z1=377*cos(x);
z2=377\cos(x);
rp=(z2*cos(t2)-z1*cos(x))/(z2*cos(t2)+z1*cos(x));
I want to calculate rp for each angle from 0 to pi/2 and then plot it. What am I doing wrong?

Every operation is perform on same cell in z1 and z2. Matlab/Ocatave calculate enquation based on variable's type. So if you put * between vectors it try to calculate cross product. Probably problem was \, I have no idea what Matlab tried to do with it. Adding . before operator change approach to more natural (for non mathematical folks) and multiply corresponding cells.
But still I'm not sure it this is what you expected
rp=(z2.*cos(t2)-z1.*cos(x))./(z2.*cos(t2)+z1.*cos(x));

First, why are you using \ in this line?
z2=377\cos(x);
There is a difference between \ and / in MATLAB.
It is time to learn about the difference between ./ and .* versus / and * in MATLAB.
When you want element-wise operations, use the operators with a dot.

Related

How to plot a polar plot?

the question
Given N=1, an antenna has a radiation pattern given as y(theta)=sin(N4pitheta)/(N4pitheta) Assume that the formula is valid over the range of . Generate a polar plot of the radiation pattern. Use 400 points for your graph.
here is my code, I keep getting "THETA and RHO must be the same size." what does this mean and how can I fix my cod? thanks
function [graph,x,y]=question3(N)
x=linspace(-pi,pi,400);
y=(sin(N*4*pi*x)/(N*4*pi*x));
graph='polar(x,y)';
end
Your problem is that you are performing matrix division, not elementwise division.
change y=(sin(N*4*pi*x)/(N*4*pi*x)) to y=(sin(N*4*pi*x)./(N*4*pi*x))
Note that in Matlab, * and / will perform matrix operations while .* and ./ will perform array operations.
Read more here.
Side note: It looks like you are using eval to evaluate the output of that function. If it is your profesor who did this, leave it, but remember that even Matlab staff themselves suggest never to use eval.

Matlab using r divide twice in one expression

If I want to calculate:
var(B(k))=sigma^2(X'X+k*I_p)^-1*(X'X)*(X'X+k*I_p)^-1
where sigma and k are constants, I_p is an identity matrix of the correct dimension and X is an n*p matrix
in MATLAB is this the correct syntax?
var_alpha_Ridge=sigma2*(Gamma+lambda)\Gamma\(Gamma+lambda);
where Gamma=(X'X) and lambda=k*eye(p).
If you want to do it via the / and \ operators, it would be
var_alpha_Ridge=sigma2*(Gamma+lambda)/Gamma\(Gamma+lambda);
However, I'd prefer to precompute the inverse
iGl = inv(Gamma+lambda);
var_alpha_Ridge=sigma2*iGl*Gamma*iGl;
If you are worried about numerical stability, use pinv instead:
iGl = pinv(Gamma+lambda);
var_alpha_Ridge=sigma2*iGl*Gamma*iGl;
Since the matrix you are inverting is probably well-conditioned because of the lambda part, I wouldn't expect large differences between the three ways to compute it.

Cepstrum deconvolution Matlab code

I have a little code, that should implement cepstrum deconvolution for minimum phase FIR filter design, but being nonmatlab guy I'm struggling with understanding it. Can someone help?
wn = [ones(1,m)
2*ones((n+odd)/2-1,m)
ones(1-rem(n,2),m)
zeros((n+od d)/2-1,m)];
y = real(ifft(exp(fft(wn.*real(ifft(log(abs(fft(x)))))))));
Mainly I don't understand the first line, ".*" symbol in second line and also probably at some point there should be conversion from real to complex domain in the second line, but I have no idea where. Any ideas?
In the first line you are constructing the matrix wn row by row.
.* operator means element-wise multiplication. * alone would mean matrix multiplication.
In fact you should pay attention to the size of x and wn which must be the same for the element-wise multiplication to have sense.
actually there isn't any conversion from real to complex in the second line. There are the functions log, fft, ifft that may return complex values depending on the input.
You can access the Matlab help by the commands help or doc (for example doc ones should produce the documentation of the ones function - this produce a matrix filled with ones of the size specified by it's arguments).
To quickly summon the help when you're inspecting some code you can use Matlab's inline help by pressing the button F1 when the cursor is at the end of a function name (just before the parenthesis).

Double integral in MATLAB

I'm trying to find the power in an aperture from a Gaussian beam, where the aperture is offset from the beam center. The solution is the following equation (reference) (sorry, no LaTeX here):
Wz is a constant, along with a and r. I'm not sure how I can do something like this with MATLAB. Does anyone have a suggestion? I know there's a dblquad() function, but it assumes that the limits of integration are fixed, and not dependent on each other.
Using a bit of mathematical footwork, you could reduce the double integral to a single one (albeit containing the error function) which should be easier to calculate numerically in MATLAB:
(With reservation for errors; check the calculations yourself if possible.)
It turns out that more recent versions of MATLAB now have a quad2d() function, which does a 2d integral over a surface. Example 2 on the reference page details an example of doing this type of integration.
My code ended up looking something like this:
powerIntegral = #(x,y) 2/(pi*W^2)*exp(-2*((x - offsetDist).^2 + y.^2)/(W^2));
ymin = #(x) -sqrt(radius.^2 - x.^2);
ymax = #(x) sqrt(radius.^2 - x.^2);
powerRatioGaussian = quad2d(powerIntegral,-radius,radius,ymin,ymax);
Pretty nifty. Thanks for the help.
I am not sure, but I think that the symbolic toolbox can help you here. It is suited for this kind of problems. You can define your variables as symbolic vars using the syms command, and compute the integral symbolically. Then, you can assign the variables values and find the actual value.
Disclaimer : I have never actually used it myself.
Generally speaking, for numeric integration, you can transform an integral with dependent boundary conditions to one with independent boundaries by multiplying by a function that is 1 if you are inside the original boundary and 0 if you are outside. Then take your limits to be a square that contains your original conditions. In other words here you would multiply by
g(x,y) = ((x^2 + y^2) < a^2)
and your limits would be -a
You have to be a little careful about the continuity assumptions in your integration method, but you should be OK unless something is very weird. You can always check by changing your cell size and making sure the computed integral value doesn't change.
In this particular case, you could also make the transformation from cartesian to polar coordinates;
x = rcos(t)
y = rsin(t)
dxdy = rdrdt
Then your limits of integration would be r from 0 to a and t from 0 to 2*pi

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.