Sine generation with variable frequency and amplitude
显示 更早的评论
Hi everyone,
I have been trying to write a code that generates series of sine wave with changing frequency and amplitude; for example a 20 Hz sine wave for 20 seconds, after it reaches to 30 Hz for 10 seconds and so on.
When with constant ouput values, there is no problem. The code I wrote for it is below
k=zeros(1,100);
t=zeros(1,100);
t=0:99;
for i=1:100;
if i<=30;
k(i)=1;
else if i<=60;
k(i)=3;
else i<=100;
k(i)=2;
end
end
end
plot(t,k)
It gives correct results. Try this one and imagine I want to change these constant values with sine waves.
When I changed k(i) values with sine, like below;
k=zeros(1,100);
t=zeros(1,100);
t=0:99;
a=linspace(0,2*pi,30);
for i=1:90;
if i<=30;
k(i)=2*sin(a);
else if i<=60;
k(i)=sin(a);
else i<=90;
k(i)=3*sin(a);
end
end
end
plot(t,k)
It gives that error;
??? In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in ==> Untitled3 at 9 k(i)=2*sin(a);
The dimensions match, Can anyone give me a hand about the code above or show any other way?
Thanks,
Ozgur Palaz
采纳的回答
更多回答(3 个)
Friedrich
2011-7-8
Hi,
You get this error because sin(a) is a vector of size 1x30 and you want assign this to a single field k(i). Maybe give k an other size
k=zeros(100,30)
and than do
k(i,:)=2*sin(a)
3 个评论
Ozgur
2011-7-8
Friedrich
2011-7-8
Sorry my fault this would be correct:
k=zeros(1,100);
t=zeros(1,100);
t=0:99;
a=linspace(0,2*pi,30);
for i=1:90;
if i<=30;
k(i)=2*sin(a(i));
else if i<=60;
k(i)=sin(a(i-30));
else i<=90;
k(i)=3*sin(a(i-60));
end
end
end
but the code from andrei is much better.
Ozgur
2011-7-8
Andrei Bobrov
2011-7-8
k= zeros(1,100);
k(1:90) = sin(linspace(0,2*pi,30))'*[2 1 3];
EDIT
k= zeros(30,100);
k(:,1:90) = reshape(permute(repmat(sin(linspace(0,2*pi,30))'*[2 1 3],[1,1,30]),[1 3 2]),30,[]);
answer on comment
1. '*[2 1 3]
eg.:
>> a = (1:3)'
a =
1
2
3
>> b = [2 1 3]
b =
2 1 3
>> a*b
ans =
2 1 3
4 2 6
6 3 9
or
>> bsxfun(@times,a,b)
ans =
2 1 3
4 2 6
6 3 9
2. Please specify question
类别
在 帮助中心 和 File Exchange 中查找有关 Audio I/O and Waveform Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!