2

Matlab 的 for 循环 « 阅微堂

 3 years ago
source link: https://zhiqiang.org/coding/for-in-matlab.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Matlab 的 for 循环

作者: 张志强

, 发表于 2009-08-05

, 共 516 字 , 共阅读 170 次

最近写了一些 Matlab 程序,想起以前想过的一个东西,记录一下。

Matlab 的 for 循环很有意思,比如下例:

i = 3;
for i = 1:i
    i=2*i
end
i=2
i=4
i=6

也就是说 Matlab 的循环变量的循环路径是在进入到 for 语句的时候就决定了,它会确定起始点,步长和终点,以后每次循环都加上步长,直到到达终点为止。所以 for i = 1:numel(a)这种写法, numel(a)也只会被计算一次(而建立中间变量 t = numel(a);然后 for i = 1:t 的写法会降低效率),这和 C 语言有本质的区别。

注意下面两个的区别:

for i = 1:100000000
    i=1;
end
for i = [1:100000000]
    i=1;
end

第一个的 1:100000000 并不会真的初始化成一个向量;而第二个会,导致内存不够无法执行。

补充:最新 2009a 版的 Matlab 遇到上面例子中的循环体内部改变循环变量的情况会给出提示,另外还有很多新功能,建议升级,虽然大了点,安装文件有 4G 多。

Q. E. D.

avatar-0.jpg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK