views:

298

answers:

6

Using the zip function, Python allows for loops to traverse multiple sequences in parallel.

for (x,y) in zip(List1, List2):

Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?

+3  A: 

If I'm not mistaken the zip function you use in python creates a pair of the items found in list1 and list2. Basically it still is a for loop with the addition that it will retrieve the data from the two seperate lists for you, instead that you have to do it yourself.

So maybe your best option is to use a standard for loop like this:

for i=1:length(a)
  c(i) = a(i) + b(i);
end

or whatever you have to do with the data.

If you really are talking about parallel computing then you should take a look at the Parallel Computing Toolbox for matlab, and more specifically at parfor

Sven
+2  A: 

Tested only in octave... (no matlab license). Variations of arrayfun() exist, check the documentation.

#!/usr/bin/octave -qf

function result = dostuff(my_ten, my_one)
  result = my_ten + my_one
endfunction

tens = [ 10 20 30 ];
ones = [ 1 2 3];

x = arrayfun(@dostuff, tens, ones);

x

Yields...

x =

   11   22   33
DMC
+3  A: 

If x and y are row vectors, you can do:

for i=[x;y]
# do stuff with i(1) and i(2)
end

With column vectors, use x' and y'.

mattiast
A: 

I second mattiast's answer.

But, to dig a little deeper, is there no way to vectorize what you're trying to accomplish and avoid the iterative for loop? Perhaps with more details about what goes on inside the loop we could help vectorize the solution...

b3
A: 

for loops in MATLAB used to be slow, but this is not true anymore.

So Vectorizing is not always the miracle solution. just use the profiler, and toc and toc functions to help you identify possible bottlenecks

should be "tic" and "toc"...
Mr Fooz
A: 

I would recommend to join the two arrays for the computation:

% assuming you have column vectors a and b
x = [a b];

for i = 1:length(a)
    % do stuff with one row...
    x(i,:);
end

This will work great if your functions can work with vectors. Then again, many functions can even work with matrices, so you wouldn't even need the loop.

BastiBechtold