If statement in a loop
古いコメントを表示
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
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 件)
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
2017 年 5 月 9 日
Jan
2017 年 5 月 9 日
In your original code you overwrite the elements of F_l in each iteration of the for c loop. What do you want to obtain instead? Currently all we see is the failing assignment of the elements of this array. But what do you want instead? "change in values as co increases" is clear, but at which index should which value appear?
sedef kocakaplan
2017 年 5 月 9 日
sedef kocakaplan
2017 年 5 月 9 日
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.
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!