MATLAB学习_控制语句:for,while,if

for循环

首先我们定义一个向量v = zeros(10, 1)

接着我们写一个 “for" 循环,让v等于 1 到 10。设v(i)等于 2 的i次方,循环最后写上“end”。

>> for i = 1:10
v(i) = 2^i;
end
>> v
v =
           2
           4
           8
          16
          32
          64
         128
         256
         512
        1024

同样也可以使用breakcontinue语句

while

>> i = 1
>> while true,
     v(i) = 999;
     i = i+1;
     if i == 6,
       break;
     end;
   end;
>> i
i =
     6

if-else

>> if i == 5,
     disp("hello");
   elseif i == 4,
     disp("world");
   else
     disp("hello, world");
   end;
hello, world
>>
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy