MATLAB Matlab summation of a complex function

AI Thread Summary
The discussion focuses on correcting a MATLAB code snippet for summing a complex function. The user initially struggles with the summation loop and is advised to initialize the sum variable before the loop. A revised code suggestion includes using an array for the sum and iterating based on the defined variable K. Additional guidance emphasizes the need to properly handle array dimensions and initialization to avoid errors during execution. The final recommendation is to ensure the loop correctly accumulates the sum across iterations.
Waxterz
Messages
4
Reaction score
0
Hi,

I need to plot the last function of this:

RB9vKTW.jpg

But I don't know how to generate the sum. I know the for loop is totally wrong, but I can't go any further. This is what I have:

FBlwCaW.jpg


K = 8;
L = 950*10^-9;
g = 2*pi/L;
v0 = 30;
v = -90:10:90;
d = 950*10^-9;
for i = 1:8;

S = exp(1i*g*(K-i)*d*(sind(v)-sind(v0)));
end
A = 20*log(abs(S)/8);
A

Can someone fix the summation loop part for me?

Thanks in advance
 
Physics news on Phys.org
You need to set S to zero before the loop, then
Code:
S = S + exp(1i*g*(K-i)*d*(sind(v)-sind(v0)));
 
DrClaude said:
You need to set S to zero before the loop, then
Code:
S = S + exp(1i*g*(K-i)*d*(sind(v)-sind(v0)));
Hi DrClaude,

I posted it on the forum, just in case I didn't found the answer myself. I knew it had something to do with setting something on zero. :)

So I tried something, I tried this:

K = 8;
L = 950*10^-9;
g = 2*pi/L;
v0 = 30;
v = -90:10:90;
d = 950*10^-9;
Ssum = 0;
for i = 1:8;
Ssum = S + Ssum;
S = exp(1i*g*(K-i)*d*(sind(v)-sind(v0)));
end
A = 20*log(abs(Ssum)/8);
AIs this equivalent to yours? Thanks for your help and quick reply, btw.
 
Yea, I'm going to do your version. Got the inner matrix dimensions degree error. Anyway thx!
 
Waxterz said:
Hi DrClaude,

I posted it on the forum, just in case I didn't found the answer myself. I knew it had something to do with setting something on zero. :)

So I tried something, I tried this:

K = 8;
L = 950*10^-9;
g = 2*pi/L;
v0 = 30;
v = -90:10:90;
d = 950*10^-9;
Ssum = 0;
for i = 1:8;
Ssum = S + Ssum;
S = exp(1i*g*(K-i)*d*(sind(v)-sind(v0)));
end
A = 20*log(abs(Ssum)/8);
AIs this equivalent to yours? Thanks for your help and quick reply, btw.
Your use of Ssum is better if you need ##S_a## afterwards. But I see a few things that could be better, and one error.

First,
Code:
for i = 1:8;
would be better as
Code:
for i = 1:K
since K is already defined. Second, since Ssum will be an array (as is S), you should initialize it as an array of zeros:
Code:
Ssum = zeros(19,1);
Finally,
Code:
Ssum = S + Ssum;
S = exp(1i*g*(K-i)*d*(sind(v)-sind(v0)));
will not work. What happens at the first and last iterations of the loop?
 

Similar threads

Replies
2
Views
2K
Replies
9
Views
5K
Replies
10
Views
3K
Replies
4
Views
2K
Replies
7
Views
3K
Replies
14
Views
3K
Back
Top