Create a subplot with two graphs subplot(2,1,x). The top plot will be your summed sinusoids and the bottom will show all the sinusoids used to create the final sinusoid. To do this, use the for loop to create a matrix that contains three vectors, one for each of the base sinusoids. Then use one command (outside your function) to plot all three together on the bottom subplot.
My code is below but I am unsure how or where to add a for loop to execute this. My thought was to store the "x" value and then plot it.
function [xx,tt] = syn_sin(fk,xk,fs,dur,tstart)
if nargin <5, tstart=0, end
if length (xk)~= length(fk)
error ('error', 'fk~=xk');
end
t= tstart: 1/(fs):dur;
x=xk(1)* exp(2*j*pi*fk(1)*t);
for k=2:length(fk);
x=xk(k) *exp(2*j*pi*fk(k)*t) +x;
end
plot(t,x),grid on

 채택된 답변

Adam Danz
Adam Danz 2020년 2월 20일
편집: Adam Danz 2020년 2월 20일

1 개 추천

The general template to build subplots within a loop
nrows = 2; % number of subplot rows
ncols = 1; % number of subplot columns
nsubs = nrows * ncols; % total number of subplots
for i = 1:nsubs
subplot(nrows, ncols, i)
plot(. . .)
end
For r2019b or later, you can used tiledlayout
nrows = 2; % number of subplot rows
ncols = 1; % number of subplot columns
nsubs = nrows * ncols; % total number of subplots
tiledlayout(nrows, ncols)
for i = 1:nsubs
nexttile()
plot(. . .)
end
Let me know if there are any questions | problems.

댓글 수: 3

Would you please be able to explain where my function is having trouble? I as able to get 2 subplots however with an error.
When I go to run this function:
[xx0,tt0] = syn_sin([0,100,250],[10,14*exp(-j*pi/3),8*j],10000,0.1,0);
The error:
Warning: Imaginary parts of complex X and/or Y arguments ignored
> In syn_sin (line 17)
In Lab2 (line 112)
Output argument "xx" (and maybe others) not assigned during call to "syn_sin".
Error in Lab2 (line 112)
[xx0,tt0] = syn_sin([0,100,250],[10,14*exp(-j*pi/3),8*j],10000,0.1,0);
Comes up using the program with the loop below:
function [xx,tt] = syn_sin(fk,xk,fs,dur,tstart)
if nargin <5, tstart=0, end
if length (xk)~= length(fk)
error ('error', 'fk~=xk');
end
t= tstart: 1/(fs):dur;
x=xk(1)* exp(2*j*pi*fk(1)*t);
for k=2:length(fk);
x=xk(k) *exp(2*j*pi*fk(k)*t) % +x;
end
nrows = 2; % number of subplot rows
ncols = 1; % number of subplot columns
nsubs = nrows * ncols; % total number of subplots
tiledlayout(nrows, ncols)
for i = 1:nsubs
nexttile()
plot(t,x),grid on
title('SYN SIN')
xlabel('TIME(sec)')
ylabel('Frequency')
end
Adam Danz
Adam Danz 2020년 2월 21일
편집: Adam Danz 2020년 2월 21일
My bet is that the variable j was not assigned a value. By default, j is an imaginary unit.
Thank you so much!!! Yes I always forget to reassign j for i.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Line Plots에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2020년 2월 20일

편집:

2020년 2월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by