Attempting to make an amplitude v frequency plot

4 views (last 30 days)
still wrapping my head around how matlab creates its plots. After performing a simple fourier series to my function i am left with:
a_n = 4/(n*pi)*sin((n*pi)/2)
were n is from -5 --> 5. The simple code I used is giving me a matrix mismatch error. Im really just not getting it:
n = -5:1:5;
a_n = 4/(n*pi).*sin(n*pi/2);
plot(n,a_n);
Error using / Matrix dimensions must agree.
Error in Untitled (line 14) a_n = 4/(n*pi).*sin(n*pi/2);
Standard error. Im after a simple line plot with the x-axis to represent frequency (-5wo, -4wo, ...4wo, 5wo) and the y-axis to be the representation of a_n. Performing this by hand is simple enough, but Id really like to be able to present a generated graph instead of a hand drawn one for this lab report.
Thanks in advance.

Accepted Answer

Star Strider
Star Strider on 23 Sep 2015
Edited: Star Strider on 23 Sep 2015
You’re needing a (./) operator with the vector in the denominator:
a_n = 4./(n*pi).*sin(n*pi/2);
You have to use element-wise array operations in that instance.
EDIT — To avoid the NaN discontinuity at zero, add small values to both the numerator and denominator as a sort of L’Hospital’s rule work-around:
a_n = 4./(n*pi+1E-10).*sin(n*pi+1E-10/2);
Another way is to define your ‘n’ vector to not have a value at zero, perhaps by using the linspace function, and use either function in my Answer with it.
  2 Comments
ray brunkow
ray brunkow on 23 Sep 2015
Thank you. That did the trick. silly little thing.
I am able to generate a nice looking plot with linspace(-5,5), but that does provide a full 100 values in that set, but id really love to get it to match properly for each integer only in that same range. When I used 10 and 11 for the spacing, the resulting graph had values over non-integer values.
Any way around that?
Thank you again.
Star Strider
Star Strider on 23 Sep 2015
My pleasure.
If you want evenly-spaced vectors that include zero and still have good resolution, you can certainly define them as such. Just use a different step in ‘n’, for instance:
n = -5 : 0.1 : 5;
or any step you want that will produce the symmetrical vector you want. MATLAB builds its colon-operator vectors by starting from both ends and meeting in the centre to minimise cumulative error, so the vectors should be symmetrical. Use the second function to avoid the NaN at zero.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!