What is the output?

3 ビュー (過去 30 日間)
Shivangi Srivastava
Shivangi Srivastava 2018 年 4 月 1 日
コメント済み: Walter Roberson 2018 年 4 月 1 日
I am trying to check how the loop works hence, I am displaying the value of n in the for loop but it doesn't seem to work. Why doesn't n get displayed and how is the code (loop) working?
h=0.3;
x=0:h:0.8;
for n=4:length((x)-1)
disp(n)
% Doing something here
end

採用された回答

Walter Roberson
Walter Roberson 2018 年 4 月 1 日
length of x is 3. When you subtract 1 from a numeric vector you do not change the length so length((x) - 1) is the same length(x) which is 3. So your for loop is
for n=4:3
Which will not execute at all.

その他の回答 (1 件)

Roger Stafford
Roger Stafford 2018 年 4 月 1 日
The vector x has only three elements, [0,.3,.6], so the 'for' instruction reads:
for n = 4:2
Therefore the loop will not execute at all, and this accounts for your lack of results.
  2 件のコメント
Shivangi Srivastava
Shivangi Srivastava 2018 年 4 月 1 日
編集済み: Shivangi Srivastava 2018 年 4 月 1 日
If h would have been 0.2 then the for loop would be n = 4:4 right? How does this code get executed and the values of n change?
Walter Roberson
Walter Roberson 2018 年 4 月 1 日
No, with 0.2 x would be 0 0.2 0.4 0.6 0.8 which is length 5. When you subtract one from the numeric values the length stays the same, just you would working with -1 -.8 -.6 -.4 -.2. Still length 5. So the loop would be 4:5

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

カテゴリ

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