Rick T
Rick T

Reputation: 3389

multiplying sin waves / cos waves recursively in a loop in matlab / octave

I'm trying to multiply sin waves / cosine waves recursively but I'm not sure why my answers are so different. Y2 in blue is what I'm trying to get but the FOR loop which is Y in red is what is produced any idea how to fix the FOR loop Y? see plot and code below ?

Fs = 8000;% Sampling frequency
t=linspace(0,1,Fs);

y=zeros(1,length(t));
y = .5*sin(2*pi*2*t); 
for ii=1:1:3    
    y=y.*y; 
end
plot(y,'r') 
hold on

y2=(.5*sin(2*pi*2*t)).* (.5*sin(2*pi*2*t)).*(.5*sin(2*pi*2*t)); %should look like this
plot(y2,'b') %both plots should look like this

Plot PS: I'm using octave 3.8.1 which is like matlab

Upvotes: 0

Views: 580

Answers (2)

KKS
KKS

Reputation: 1389

In all iteration, y.*y make square of updated y.

Fs = 8000;% Sampling frequency
t=linspace(0,1,Fs);

y=ones(1,length(t));
x = .5*sin(2*pi*2*t); 
for ii=1:1:3    
    y=y.*x; 
end
plot(y,'r') 
hold on

y2=(.5*sin(2*pi*2*t)).* (.5*sin(2*pi*2*t)).*(.5*sin(2*pi*2*t)); %should look like this
plot(y2,'b') %both plots should look like this

Maybe, you want this code.

Upvotes: 2

jrhee17
jrhee17

Reputation: 1152

You're multiplying eight times here

y = .5*sin(2*pi*2*t); 
for ii=1:1:3    
     y=y.*y; 

ii=1:1:3 is inclusive, so you do y=y.*y three times.

First time it becomes y = y^2,

Second time it become y^4 = y^2*y*2

Third time it becomes y^8 = y^4*y^4


This would be a solution:

Fs = 8000;% Sampling frequency
t=linspace(0,1,Fs);

y=zeros(1,length(t));
y = .5*sin(2*pi*2*t); 
result = ones(1,length(t));
for ii=1:1:3
     result=result.*y; 
end
plot(result,’r’) 
hold on

y2=(.5*sin(2*pi*2*t)).* (.5*sin(2*pi*2*t)).*(.5*sin(2*pi*2*t)); %should look like this
plot(y2,'b') %both plots should look like this

Upvotes: 3

Related Questions