MATLAB中有foreach吗?如果是这样,如果基础数据发生变化,它会如何表现? [英] Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

查看:16
本文介绍了MATLAB中有foreach吗?如果是这样,如果基础数据发生变化,它会如何表现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MATLAB 中有 foreach 结构吗?如果是这样,如果底层数据发生变化(即如果对象被添加到集合中)会发生什么?

Is there a foreach structure in MATLAB? If so, what happens if the underlying data changes (i.e. if objects are added to the set)?

推荐答案

MATLAB 的 FOR 循环本质上是静态的;您不能在迭代之间修改循环变量,这与其他语言中的 for(initialization;condition;increment) 循环结构不同.这意味着无论 B 的值如何,以下代码始终打印 1, 2, 3, 4, 5.

MATLAB's FOR loop is static in nature; you cannot modify the loop variable between iterations, unlike the for(initialization;condition;increment) loop structure in other languages. This means that the following code always prints 1, 2, 3, 4, 5 regardless of the value of B.

A = 1:5;

for i = A
    A = B;
    disp(i);
end

如果您希望能够在迭代过程中响应数据结构的变化,一个 WHILE 循环 可能更合适 --- 您将能够在每次迭代时测试循环条件,并设置循环变量的值) 如您所愿:

If you want to be able to respond to changes in the data structure during iterations, a WHILE loop may be more appropriate --- you'll be able to test the loop condition at every iteration, and set the value of the loop variable(s) as you wish:

n = 10;
f = n;
while n > 1
    n = n-1;
    f = f*n;
end
disp(['n! = ' num2str(f)])

顺便说一句,for-each 循环 在 Java 中(可能还有其他语言)在迭代期间修改数据结构时会产生未指定的行为.如果需要修改数据结构,应该使用适当的Iterator 实例,它允许添加和删除您正在迭代的集合中的元素.好消息是 MATLAB 支持 Java 对象,因此您可以执行以下操作:

Btw, the for-each loop in Java (and possibly other languages) produces unspecified behavior when the data structure is modified during iteration. If you need to modify the data structure, you should use an appropriate Iterator instance which allows the addition and removal of elements in the collection you are iterating. The good news is that MATLAB supports Java objects, so you can do something like this:

A = java.util.ArrayList();
A.add(1);
A.add(2);
A.add(3);
A.add(4);
A.add(5);

itr = A.listIterator();

while itr.hasNext()

    k = itr.next();
    disp(k);

    % modify data structure while iterating
    itr.remove();
    itr.add(k);

end

这篇关于MATLAB中有foreach吗?如果是这样,如果基础数据发生变化,它会如何表现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆