Help with for loop
显示 更早的评论
I need help or direction on for loops given the question
Use a loop to create a vector vout that contains the 5‐value moving average of vin. Since it takes 5 values of input to create the first value in the output, there will be a slight delay in the output. In other words, the first non‐zero value of vout will occur at the 5th position of vout and will be the average of vin(1) through vin(5).
given information
f1 = 100; % The lower frequency in cycles per second
f2 = 400; % The higher frequency in cycles per second
w1 = 2*pi*f1; % The lower frequency in radians per second
w2 = 2*pi*f2; % The higher frequency in radians per second
T1 = 1/f1; % The period of the lower frequency
T2 = 1/f2; % The period of the higher frequency
ns = 20; % Number of samples per period of high freq. component
% Plot the signal over 4 periods of the lower frequency component. The
% increment of the composite signal will be the period of the higher
% frequency component divided by ns.
t = (0:T2/ns:4*T1);
vin = cos(w1.*t) + cos(w2.*t);
vout(k) = (vin(k) + vin(k-1) + vin(k-2) + vin(k-3) + vin(k-4) ) / 5
This is what i tried
for k= 5:90;
vout(k) = (vin(k) + vin(k-1) + vin(k-2) + vin(k-3) + vin(k-4) ) / 5
end
plot(k,vin)
plot(k,vout)
3 个评论
Guillaume
2014-11-19
Your loop is fine (assuming that there's 90 elements in vin), so what is your problem?
I wouldn't hard code the upper bound and would use numel(vout) instead.
Your plot look weird, the first argument (k) is scalar but that has nothing to do with the for loop.
benny
2014-11-19
Guillaume
2014-11-19
plot(vin);
plot(5:numel(vout), vout);
should solve that (assuming hold all). But again, that has nothing to do with the loop. Since your question is about the loop, again, what problem are you having with it?
采纳的回答
更多回答(1 个)
MA
2014-11-19
you have common mistakes,here your correct code:
clear all
close all
clc;
f1 = 100; % The lower frequency in cycles per second
f2 = 400; % The higher frequency in cycles per second
w1 = 2*pi*f1; % The lower frequency in radians per second
w2 = 2*pi*f2; % The higher frequency in radians per second
T1 = 1/f1; % The period of the lower frequency
T2 = 1/f2; % The period of the higher frequency
ns = 20; % Number of samples per period of high freq. component
% Plot the signal over 4 periods of the lower frequency component. The
% increment of the composite signal will be the period of the higher
% frequency component divided by ns.
t = (0:T2/ns:4*T1);
vin = cos(w1.*t) + cos(w2.*t);
for k=5:90
vout(k) = (vin(k) + vin(k-1) + vin(k-2) + vin(k-3) + vin(k-4) ) / 5;
end
k=5:90;
voutn(1,:)=vout(5:90);
subplot(2,1,1)
plot(t,vin)
title('vin')
subplot(2,1,2)
plot(k,voutn)
title('vout')
类别
在 帮助中心 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!