If statement in a loop

1 次查看(过去 30 天)
sedef kocakaplan
sedef kocakaplan 2017-5-9
评论: Jan 2017-5-10
Hi everyone,
I am trying to run the code below. The problem is co is not working in a loop. I just obtained the last raw for the computation. What should I do to work the code with a looping co?(F_l is a force vector)
co = 1;
for c = 1:na-2
co=co+1
for ni = 3:3:length((reale))
if ni==3;
F_l(ni) = 2*pi*((DeltaR/na)/6);
elseif ni==6;
F_l(ni) =2*pi*( ((DeltaR/na)/3)+ (2/na+2/na)*DeltaR/6);
elseif ni==length((reale));
F_l(ni)=2*pi*((na-1)/na+2)*DeltaR/6;
else
F_l(ni) =2*pi*( ((DeltaR*((co-1)/na+2*co/na))/6)+ ((DeltaR*((co+1)/na+2*co/na))/6)) ;
end
end
end
  1 个评论
Jan
Jan 2017-5-9
The question is not clear. Of course you can use co inside a loop and inside the if branches. Please explain what "co is not working" exactly means. What does "the last row for the computation" mean?

请先登录,再进行评论。

回答(1 个)

Jan
Jan 2017-5-9
编辑:Jan 2017-5-9
With some guessing:
co = 1;
F_l = zeros(length(reale), na - 2); % Pre-allocate!!!
for c = 1:na-2
co = co + 1;
for ni = 3:3:length(reale)
if ni == 3
F_l(ni, c) = 2*pi*((DeltaR/na)/6);
elseif ni == 6
F_l(ni, c) = 2*pi*(((DeltaR/na)/3) + (2/na+2/na)*DeltaR/6);
elseif ni == length(reale)
F_l(ni, c) = 2*pi*((na-1)/na+2)*DeltaR/6;
else
F_l(ni, c) = 2*pi*(((DeltaR*((co-1)/na+2*co/na))/6) + ...
((DeltaR*((co+1)/na+2*co/na))/6));
end
end
end
Is this the wanted result? Should F_l contain the zeros for ni=1,2, etc.? Then the code can be simplified:
co = 1;
nr = length(reale);
F_l = zeros(nr, na - 2); % Pre-allocate!!!
F_l(3, 1:na-2) = 2*pi*((DeltaR/na)/6);
F_l(6, 1:na-2) = 2*pi*(((DeltaR/na)/3) + (2/na+2/na)*DeltaR/6);
F_l(nr, 1:na-2) = 2*pi*((na-1)/na+2)*DeltaR/6;
for c = 1:na-2
co = co + 1;
F_l(9:3:length(reale)-3, c) = 2*pi*(((DeltaR*((co-1)/na+2*co/na))/6) + ...
((DeltaR*((co+1)/na+2*co/na))/6));
end
And even this can be written without a loop.
  5 个评论
sedef kocakaplan
sedef kocakaplan 2017-5-9
Dear Jan,
I re-write the code in a different way. Thanks for your comments.
Jan
Jan 2017-5-10
@sedef kocakaplan: This is not clear: "For co 2,3,4... F_l(ni=9,12,15...) should be written." These are 2 loop counters: one for co and one for ni. But you get one vector as output only.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by