Sine generation with variable frequency and amplitude
Show older comments
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
Accepted Answer
More Answers (3)
Friedrich
on 8 Jul 2011
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 Comments
Ozgur
on 8 Jul 2011
Friedrich
on 8 Jul 2011
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
on 8 Jul 2011
Andrei Bobrov
on 8 Jul 2011
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
Ozgur
on 8 Jul 2011
0 votes
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!