Reputation: 5489
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.
Upvotes: 2
Views: 839
Reputation: 125874
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.
Upvotes: 4
Reputation: 124563
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')) )
You can simply change the vector p
to your specific values
Upvotes: 8