The for loop doesn't iterate

后端 未结 2 979
说谎
说谎 2021-01-12 12:41

In MATLAB the following for loop:

for i = [1:100]\' 
    %\'// Do something, such as disp(i)
end

isn\'t apparently really impl

相关标签:
2条回答
  • 2021-01-12 12:59

    If you write

    for i = (1:100)' %'# square brackets would work as well
       doSomething
    end
    

    the loop is executed only once, since a for-loop iterates over all columns of whatever is to the right of the equal sign (it would iterate 200 times with a 100-by-200 array to the right of the equal sign).

    However, in your example, you have i=[1:100], which evaluates to a row vector. Thus, the loop should execute 100x.

    If you iterate over an array that might be nx1 instead of 1xn, you can, for safety reasons, write:

    for i = myArray(:)'  %'# guarantee nx1, then transpose to 1xn
    end
    
    0 讨论(0)
  • 2021-01-12 13:16

    This is not correct. The code:

    for i=1:100
        disp(i)
    end
    

    will print all the values 1 through 100 consecutively. While Matlab does encourage vectorization, you can definitely use traditional loops with the style of coding you used above.

    0 讨论(0)
提交回复
热议问题