Using for loop for summation of sinusoids

3 次查看(过去 30 天)
Write a MATLAB function called harmonic to generate the signal r(t). The inputs to this function should be the scalar w0, containing the fundamental frequency, the vectors Cn, thetan, the maximum time tmax, and the sampling interval Tsample. The output of the function should be the vector r containing the signal r(t) sampled at the specified values of time t. Your function may use either a for loop or a matrix multiply to implement the summation. If you use a for loop, only one such loop should be necessary.
(b) Use the following values for the inputs to your function harmonic:
>> w0 = 2*pi*440;
>> Tsample = 1/(50*440);
>> Cn=[0 1];
>> thetan = [0 0];
to create a signal r1 of length tmax = 100*2*pi/w0 or, equivalently, nper = 100. Make a fully-labeled plot of the first four periods of r1(t) versus time t. Listen to the sound using the command
>> soundsc(r1,1/Tsample)
and describe what the signal sounds like.
----------
What I have so far is:
function[r] = harmonic(w0,Cn,theta,tmax,Tsample)
w0 = 2*pi*440;
Tsample = 1/50*440;
Cn = [0 1];
thetan = [0 0]
tmax = (100*2*pi)/w0;
for t = 0:Tsample:tmax;
r(t) = Cn.*cos(w0*t+thetan);
end
end
Really need help in how to write the for loop and get the sound to work!

采纳的回答

Walter Roberson
Walter Roberson 2016-9-13
t_values = 0:Tsample:tmax;
for tidx = 1 : length(t_values)
t = t_values(tidx);
...
r(tidx) = ...
end
This separates out using t as a value, from using t as an index. You are creating a vector, not a symbolic formula, and vectors need to be indexed by positive integers.

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by