两个同时for循环MATLAB或C ++ [英] Two simultaneous for loops MATLAB or C++

查看:374
本文介绍了两个同时for循环MATLAB或C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行两个依赖的非嵌套for循环.本质上,它们是两个同时的马尔可夫链,其中一个循环需要检查另一个循环中的值.是否有正确的方法来做到这一点?有没有避免的错误/无效方法?

I'd like to run two dependent non-nested for loops. In essence they are two simultaneous Markov chains, where one loop needs to check a value in the other loop. Is it there a right way to do this? Is there a wrong/inefficient way to avoid?

虚构示例:

想象一下,两个人正围着房间走来走去,摸着东西:我将他们触摸到的东西记录在两个单独的阵列中.那是我的两个 Chains for 循环.只要他们的行为是独立的就可以.但是我想改变这一点,因此他们将不得不(实时)对其他人的所作所为作出反应.这可能吗(肯定是)?

Imagine two people are walking round a room and touching things: I record those things they touch in two separate arrays. Those are my two Chains or for loops. That's fine as long as their behaviour is independent. But I'd like to change that and so they will have to react (in real-time) to what the other person is doing. Is this possible to do (surely yes)?

例如,循环1看起来像

for k=1:n
    do something

     %check loop 2
     if something is equivalent
          moves=n;
     end        
end

NB.从技术上讲,它可以一个接一个地循环执行,但是我正在寻找可以实时运行的东西.

NB. Technically it could be done one loop after the other, but I'm looking to run something in real-time if possible.

推荐答案

您可能希望将其构造为一个同时处理两个链的 for 循环.用伪代码

You probably want to construct this as one for loop that processes both chains simultaneously. In pseudocode

for k = 1:n
    compute step k of chain 1
    compute step k of chain 2

    deal with interaction between chains

您将希望将每个链打包到一个可以传递给函数的数据结构中,这样您就不必在修改了变量名的情况下重复两次计算步骤k"代码.

You will want to package each chain in a data structure that can be passed to a function, so that you do not have to repeat the "compute step k" code twice with variable names modified.

仅当此串行方法太慢时,才担心并行化.

Worry about parallelizing only if this serial approach is too slow.

这篇关于两个同时for循环MATLAB或C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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