tags:

views:

62

answers:

2

I do the following in MATLAB and it works well. However I need to calculate 20 sinusoids instead of 3 and then plot them all.

x=sin(1*w*t)*(2/(pi*1));
y=sin(3*w*t)*(2/(pi*3));
z=sin(6*w*t)*(2/(pi*6));

plot(t,x,t,y,t,z)

I figure it should be possible to make a for-loop and then plot but I'm not sure how that's done and need some help.

+7  A: 

Consider this example:

w = 2;
t = (0:0.05:pi)';              %'# time axis
p = [1 3:3:12];                %# parameters you loop over

%# sinusoids over all possible parameters
x = bsxfun(@times, sin(w*bsxfun(@times,p,t)), (2./(pi*p)));
plot(t,x)                      %# plot all of them at one
legend( cellstr(num2str(p')) )

alt text

You can simply change the vector p to your specific values

Amro
+4  A: 

The function BSXFUN is one way to solve your problem, as illustrated by Amro. However, if you are a newer MATLAB user a simpler for-loop solution may be easier to understand and a little less intimidating:

w = 1;     %# Choose the value of w
k = 1:20;  %# Your 20 values to compute a sinusoid for
N = 100;   %# The number of time points in each sinusoid

t = linspace(0,2*pi,N).';  %'# A column vector with N values from 0 to 2*pi
X = zeros(N,numel(k));      %# A matrix to store the sinusoids, one per column

for iLoop = 1:numel(k)      %# Loop over all the values in k
  X(:,iLoop) = sin(k(iLoop)*w*t)*(2/(pi*k(iLoop)));  %# Compute the sinusoid
                                                     %#   and add it to X
end

plot(t,X);  %# Plot all the sinusoids in one call to plot

Here are some links to the documentation that should be helpful in fully understanding how the above solution works: LINSPACE, NUMEL, ZEROS, PLOT, For loops, Preallocating arrays to improve performance.

gnovice
+1 I guess you're right, those BSXFUN calls look scary ;)
Amro
@gnovice: I was about to post a similar solution, though I would have plotted inside the loop, since `hold on` is a useful command to know.
Jonas
Ya BSXFUN freaked me out a bit, even if it worked, so I will go with your solution. However if I only want to plot odd numbers of K how do I do that? I tried to add this but I still plot the signal (but constant 0) var = mod(iLoop,2); if var == 0 X(:,iLoop) = sin(k(iLoop)*w*t)*(2/(pi*k(iLoop)));
Mikael
@Jonas: The only downside to that is that PLOT won't automatically color the lines differently when it is called multiple times.
gnovice
I guess an idea could be to just do define K for odd numbers?
Mikael
@Mikael: If you only want to compute and plot sinusoids for odd values of `k`, you can just change the line at the top to `k = 1:2:20;`, which will generate the numbers `[1 3 5 7 9 11 13 15 17 19]`. For more info, check out the documentation for the [colon operator](http://www.mathworks.com/help/techdoc/ref/colon.html).
gnovice
@gnovice: You're right, you'd also need to define a colormap.
Jonas

related questions