Two simultaneous for loops MATLAB or C++

纵饮孤独 提交于 2021-02-10 07:34:33

问题


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?

Imaginary example:

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)?

For example, Loop 1 would look something like

for k=1:n
    do something

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

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


回答1:


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

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.



来源:https://stackoverflow.com/questions/8955510/two-simultaneous-for-loops-matlab-or-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!