Cumulative sinusoidal wave plotting
5 次查看(过去 30 天)
显示 更早的评论
Question: I have to plot a cosine wave starting from 1 Hz. After plotting 1Hz cosine wave, increase the frequency to 2Hz and add 1Hz and 2Hz together and plot it. This has to be done till 9Hz. For the summation, need to use a 'for loop'.
Here is my attempted code:
f=1;
t=-10:0.1:10;
y2=0; %counter
for i=1:8
y1=sin(2*pi*f*t); %plotting
y3=y2+y1; %summing
y2=y3; %storing the value for next iteration
f=f+1; %increment of f
end
subplot(811)
plot(t,y3(1));
subplot(812)
plot(t,y3(2));
subplot(813)
plot(t,y3(3));
subplot(814)
plot(t,y3(4));
subplot(815)
plot(t,y3(5));
subplot(816)
plot(t,y3(6));
subplot(817)
plot(t,y3(7));
subplot(818)
plot(t,y3(8));
After running the code, it shows no error, but the plots are blank.
- I am guessing somehow my loops are getting overwritten. What is the mistake I am doing?
- Also, is there any way to implement subplots dynamically so I don't have to write them manually?
If you know any answer/answers to my questions, kindly help. Thank you!
0 个评论
采纳的回答
Star Strider
2019-9-7
Subscript in the loop, and add the second subscript reference in your plot calls.
Try this:
f=1;
t=-10:0.1:10;
y2=zeros(size(t)); %counter
for i=1:9
y1=sin(2*pi*f*t); %plotting
y3(i,:)=sum([y2; y1]); %summing
y2=y3; %storing the value for next iteration
f=f+1; %increment of f
end
subplot(811)
plot(t,y3(1,:));
subplot(812)
plot(t,y3(2,:));
subplot(813)
plot(t,y3(3,:));
subplot(814)
plot(t,y3(4,:));
subplot(815)
plot(t,y3(5,:));
subplot(816)
plot(t,y3(6,:));
subplot(817)
plot(t,y3(7,:));
subplot(818)
plot(t,y3(8,:));
This appears to do what you describe.
Experiment to get the result you want.
2 个评论
Star Strider
2019-9-7
As always, my pleasure!
Sure!
- The ‘y2’ vector needs to be the same size as ‘y1’ in order to do the addition. This creates it as such initially.
- It is necessary for ‘y3’ to be a row vector, and the sum function by default sums along the first dimension (rows), so that every addition produces a new row vector. Doing a simple addition such as ‘y2+y1’ adds them element-wise only, so as ‘y3’ adds rows, will give an eroneous result. It also results in a matrix of increasing row size, instead of the single row vector desired. (I discovered that when I first ran the code.)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Line Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!