用if/else结构和逻辑数组创建等式
逻辑数组经常被用来替代for循环中的if/else结构。
把逻辑运算当作一个屏蔽来选择数组中的某些元素进行运算。如果你要利用那些没有被选择到的元素进行运算,只需要在逻辑屏蔽上加一个非运算符(~­)。
例如,假设我们要计算一个二维数组中所有的大于5的元素的平方根,然后其余的数的平方。利用循环和选择结构的代码如下:
for ii = 1:size(a,1) for jj = 1:size(a,2) if a(ii,jj) > 5 a(ii,jj) = sqrt(a(ii,jj)); else a(ii,jj) = a(ii,jj)^2; end end end
用逻辑数组运算的代码如下:
b = a > 5 a(b) = sqrt(a(b)); a(~b) = a(~b) .^2;
显然用逻辑数组的方法运算速度要快得多。
测试4.1
本测试提供了一个快速的检查方式,看你是否掌握了4.1到4.3的基本内容。如果你对本测试有疑问,你可以重读4.1到4.3,问你的老师,或和同学们一起讨论。在附录B中可以找到本测试的答案。
检测下列for循环,说出它们的循环次数:
1. for index = 7:10 2. for jj = 7:-1:10 3. for index = 1:10:10 4. for ii = -10:3:-7 5. for kk = [0 5; 3 3]
检测下列循环,确定循环指数ires的最终值。
6. ires = 0; for index = 1:10; ires = ires + 1; end 7. ires = 0; for index = 1:10; ires = ires + index; end 8. ires = 0; for index1 = 1:10; for index2 = index1:10 if index2 == 6 break; end ires = ires + 1; end end 9. ires = 0; for index1 = 1:10; for index2 = index1:10 if index2 == 6 continue; end ires = ires + 1; end end
|