フィルターのクリア

Skipping Iterations in a For Loop

82 ビュー (過去 30 日間)
Scott Banks
Scott Banks 2023 年 7 月 23 日
コメント済み: Voss 2023 年 7 月 23 日
Hi there, I have a vector
FEM = [-16 16 -18 12 -6 6]
FEM = 1×6
-16 16 -18 12 -6 6
I want to add together (16 + -16), (-18 +_16). (12-18) and (6 + -6)
I have been trying to use a for loop with the code:
for i = 1:6-1
FEM(i+1) + FEM(i)
end
ans = 0
ans = -2
ans = -6
ans = 6
ans = 0
However, from this I get one extra value that I do not want as shown, which is postive 6. What I really want is just [0 -2 -6 0].
I did a quick look up and came across the 'continue' function which should skip an iteration. So I set up the code like this:
for i = 1:6-1
FEM(i+1) + FEM(i)
if i ==3
continue
end
end
ans = 0
ans = -2
ans = -6
ans = 6
ans = 0
but look, I still get the five values instead of the four!
Could somebody help please?
Many thanks in advance!

採用された回答

Voss
Voss 2023 年 7 月 23 日
Basically you have to put the continue before the stuff you want to skip.
FEM = [-16 16 -18 12 -6 6];
for i = 1:6-1
if i ==3
continue
end
FEM(i+1) + FEM(i)
end
ans = 0
ans = -2
ans = 6
ans = 0
  2 件のコメント
Scott Banks
Scott Banks 2023 年 7 月 23 日
Thannk you very much, Voss!
Voss
Voss 2023 年 7 月 23 日
You're welcome!

サインインしてコメントする。

その他の回答 (1 件)

Torsten
Torsten 2023 年 7 月 23 日
編集済み: Torsten 2023 年 7 月 23 日
FEM = [-16 16 -18 12 -6 6];
n = numel(FEM);
for i = 1:n-3
FEM(i+1) + FEM(i)
end
ans = 0
ans = -2
ans = -6
FEM(end) + FEM(end-1)
ans = 0

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by