📜  MATLAB for循环

📅  最后修改于: 2021-01-07 02:15:26             🧑  作者: Mango

MATLAB for循环

for循环用于循环语句特定次数。并且还使用递增或递减的索引变量来跟踪每次迭代。

句法:

for index = values
 
 ...    
end

范例1:

% program to print multiples of first prime number between 1000 and 2000
% using for loop
pr = 0;
for k = 1000:2000
    if isprime(k)
        pr = k;
        disp(['The first prime number is : ',num2str(pr)])
        for m = pr:pr:pr*10
            disp(m)
        end
        
        break
    end
end

输出:

The first prime number is: 1009
        1009

        2018

        3027

        4036

        5045

        6054

        7063

        8072

        9081

       10090

范例2:

for a = 10:20
 fprintf('value of a: %d\n', a);
end

输出:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

范例3:

for a = 1.0: -0.1: 0.0
 disp(a)
end

输出:

1
9/10
4/5
7/10
3/5
1/2
2/5
3/10
1/5
1/10
0