If statement in a loop

1 view (last 30 days)
sedef kocakaplan
sedef kocakaplan on 9 May 2017
Commented: Jan on 10 May 2017
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 Comment
Jan
Jan on 9 May 2017
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?

Sign in to comment.

Answers (1)

Jan
Jan on 9 May 2017
Edited: Jan on 9 May 2017
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 Comments
sedef kocakaplan
sedef kocakaplan on 9 May 2017
Dear Jan,
I re-write the code in a different way. Thanks for your comments.
Jan
Jan on 10 May 2017
@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.

Sign in to comment.

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!