How to convert from a for loop to a while loop

3 ビュー (過去 30 日間)
Yuqing Zhu
Yuqing Zhu 2016 年 12 月 13 日
編集済み: James Tursa 2016 年 12 月 13 日
I need to modify the set of codes below to a while loop
  3 件のコメント
James Tursa
James Tursa 2016 年 12 月 13 日
編集済み: James Tursa 2016 年 12 月 13 日
Why do you need this converted? Is this homework? Why not get rid of the loop entirely and vectorize this operation?
Yuqing Zhu
Yuqing Zhu 2016 年 12 月 13 日
編集済み: James Tursa 2016 年 12 月 13 日
I do like this from lecture note, but doesn't work well. Anything wrong happened?
Vector = [3 -3 2 -6 1 -9];
Index = 1;
while Index <= length(Vector);
if(Vector(Index)<0);
continue
else
Vector(Index) = Vector(Index) * 2;
end
Index=Index+1;
end
disp(Vector)

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

採用された回答

James Tursa
James Tursa 2016 年 12 月 13 日
編集済み: James Tursa 2016 年 12 月 13 日
Your loop doesn't work because the "continue" statement skips over the Index=Index+1 statement. You need to rewrite things without skipping over that statement ... e.g., maybe try to rewrite your if-then-else stuff so that you do not use a "continue" statement. (Hint: What happens to your logic if you simply comment out that "continue" statement?)
  2 件のコメント
Yuqing Zhu
Yuqing Zhu 2016 年 12 月 13 日
This question is from my review session. Use another way to do the same job maybe should be while loop. I have no idea to do the same job
James Tursa
James Tursa 2016 年 12 月 13 日
編集済み: James Tursa 2016 年 12 月 13 日
See my hint about how to get your while loop version working. Or see Dave Barry's one-liner.

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

その他の回答 (1 件)

David Barry
David Barry 2016 年 12 月 13 日
This does not need to be any kind of loop. You should learn about logical indexing in MATLAB. This can be done with one line of code.
Vector(Vector >=0) = Vector(Vector >=0) * 2;

カテゴリ

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