Is it possible for a matlab script to run two different functions at the same time Is it possible for a matlab script to run two different functions at the same time multithreading multithreading

Is it possible for a matlab script to run two different functions at the same time


It is not possible for Matlab to run more than 1 function at a time. Matlab is a strictly single-threaded programing environment, i.e., it executes the commands in the scripts in sequence. User can not write any multi-threaded code in Matlab directly. Some in-built Matlab functions do support multi-threading, and you can e.g. write a multi-threaded MEX function, but there are severe limitations: Matlab MEX interface (e.g., memory allocation) is not thread safe, so you either allocate in one thread, or use barriers before any call to Matlab functionality.

Sometimes you can use the timer functionality to "interrupt" the execution of a program and do something in the mean time, but there is still only one execution path at any given moment.

Also, you can start multiple workers in the Parallel Processing Toolbox. However, the "master" script is still single threaded and waits for the completion of the workers to obtain the results of computations.


What you want is called threaded operations. Matlab has pretty limited support for such things, but there is some. In particular, there is the batch command. Of course, this assumes you have the parallel processing toolkit.

batch start_function

In general, however, the same thing could be accomplished by a more careful loop, where you first get actions, then make the actions happen. Some actions could happen over the course of several frames, if you carefully keep track of the states. To turn your code into this would be complex, but let me show you the basic idea (This code won't run, but should show you roughly what to do):

player1_jump=falseplayer2_jump=false;while(true)   key=getKey();   if key==PLAYER1_JUMP_KEY      player1_jump=true;   end   if key==PLAYER2_JUMP_KEY      player2_jump=true;   end   if player1_jump      %Move player 1 one step      if (done) %Put in your own criteria          player1_jump=false;      end   end   if player2_jump      %Move player 2 one step      if (done) %Put in your own criteria          player2_jump=false;      end   endend

Note that you'd have to keep track of where in the jump each player is, etc. Also, a small pause statement would be required to get the gui updated. But the general pattern should hold, and I'll leave you to work out the details.


You might want to look into

parfor

It is a way of performing operations in parallel. I'm not positive if this is what you are looking for exactly, but it seems to match your description

http://www.mathworks.com/help/matlab/ref/parfor.html