Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>MATLAB's <strong>FOR</strong> loop is static in nature; you cannot modify the loop variable between iterations, unlike the <strong>for(initialization;condition;increment)</strong> loop structure in other languages. This means that the following code always prints 1, 2, 3, 4, 5 regardless of the value of B.</p> <pre><code>A = 1:5; for i = A A = B; disp(i); end </code></pre> <p>If you want to be able to respond to changes in the data structure during iterations, a <a href="https://www.mathworks.com/help/matlab/ref/while.html?s_tid=doc_ta" rel="noreferrer"><strong>WHILE</strong> loop</a> may be more appropriate --- you'll be able to test the loop condition at every iteration, and set the value of the loop variable(s) as you wish:</p> <pre><code>n = 10; f = n; while n &gt; 1 n = n-1; f = f*n; end disp(['n! = ' num2str(f)]) </code></pre> <p>Btw, the <strong>for-each</strong> loop <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html" rel="noreferrer">in Java</a> (and possibly other languages) produces unspecified behavior when the data structure is modified during iteration. If you need to modify the data structure, you should use an appropriate <strong><a href="http://java.sun.com/javase/6/docs/api/java/util/Iterator.html" rel="noreferrer">Iterator</a></strong> instance which allows the addition and removal of elements in the collection you are iterating. The good news is that MATLAB supports Java objects, so you can do something like this:</p> <pre><code>A = java.util.ArrayList(); A.add(1); A.add(2); A.add(3); A.add(4); A.add(5); itr = A.listIterator(); while itr.hasNext() k = itr.next(); disp(k); % modify data structure while iterating itr.remove(); itr.add(k); end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload