Matlab中的continue、break和return语句

您所在的位置:网站首页 matlab里面的循环语句 Matlab中的continue、break和return语句

Matlab中的continue、break和return语句

#Matlab中的continue、break和return语句| 来源: 网络整理| 查看: 265

Continue: 经常用在for和while语句中,continue一旦被执行,就会终止当前循环,进行下一次循环。 eg, 在for 循环中:

clc clear all close all i = 1; COND = 1; for i = 1:20 if mod(i,2)==0 continue else fprintf('the array is %d\n',i) end end

结果是:

the array is 1 the array is 3 the array is 5 the array is 7 the array is 9 the array is 11 the array is 13 the array is 15 the array is 17 the array is 19

我们跳过了能够被2整除的数字,找出来了剩下的数字。

eg, 在while 循环中:

clc clear all close all i = 1; COND = 1; while COND ==1 if mod(i,2)==0 i = i+1; continue; else fprintf('the array is %d\n',i) end if i>=19 COND = 2; end i = i+1; end

这里可以看到,我们在符合while条件下的循环中,如果被2整除了,那么就会跳过这个循环,直接进到下一个while循环下,从头开始执行。再一次进入if 判断新的i是否满足整除要求。

结果如下:

the array is 1 the array is 3 the array is 5 the array is 7 the array is 9 the array is 11 the array is 13 the array is 15 the array is 17 the array is 19

break:

break和continue用法相似,区别在于,一旦执行了break, 就会推出循环,而不是进入下一个循环:

在for循环中: 我们在1:10中,到一个被3整除的,一旦找到了第一个,整个for循环就不会再执行了。但是要注意,只是不执行break所在的循环,其他的循环还是要执行的。

clc clear all close all i = 1; COND = 1; for i = 1:10 if mod(i,3)==0 break else fprintf('the array is %d\n',i) end end

结果为:

the array is 1 the array is 2

如果我们人工的在添加一个for 循环:

%% clc clear all close all i = 1; COND = 1; for j = 1:4 for i = 1:j if mod(i,3)==0 break else fprintf('the array is %d\n',i) end end end

结果为:

the array is 1 the array is 1 the array is 2 the array is 1 the array is 2 the array is 1 the array is 2

我们会把外层的for 循环全部执行完。

return: return 跳出函数,返回调用函数处。 无论是while还是for,直接跳出函数,返回到调用函数之前。

%% clc clear all close all i = 1; COND = 1; for i = 1:20 if mod(i,2)==0 return else fprintf('the array is %d\n',i) end end %% clc clear all close all i = 1; COND = 1; while COND ==1 if mod(i,2)==0 i = i+1; return; else fprintf('the array is %d\n',i) end if i>=19 COND = 2; end i = i+1; end

执行这两段函数都是一个结果:

the array is 1 >>

当i = 2时,函数就跳出了。

用一个更简单的例子说明,我们有一个很多层的if else 判断语句,这个时候用return 就很好,如果符合条件就可以直接跳出多层if else语句,而不需要把所有的if else 全部执行一遍再跳出。

clc clear all close all flag = 20 ; if flag 20 fprintf('y>20\n') return elseif flag >=-10 && flag =19 COND = 2; end i = i+1; end %% clc clear all close all i = 1; COND = 1; for i = 1:4 if mod(i,3)==0 break else fprintf('the array is %d\n',i) end end %% clc clear all close all i = 1; COND = 1; for j = 1:4 for i = 1:j if mod(i,3)==0 break else fprintf('the array is %d\n',i) end end end %% clc clear all close all i = 1; COND = 1; for i = 1:20 if mod(i,2)==0 return else fprintf('the array is %d\n',i) end end %% clc clear all close all i = 1; COND = 1; while COND ==1 if mod(i,2)==0 i = i+1; return; else fprintf('the array is %d\n',i) end if i>=19 COND = 2; end i = i+1; end %% clc clear all close all flag = 20 ; if flag 20 fprintf('y>20\n') return elseif flag >=-10 && flag


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3