Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can parallel traversals be done in MATLAB just as in Python?

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?

like image 328
Jason Avatar asked Sep 08 '08 08:09

Jason


2 Answers

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

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

(with row vectors, just use x and y).

Here is an example run:

>> x=[1 ; 2; 3;]

x =

     1
     2
     3

>> y=[10 ; 20; 30;]

y =

    10
    20
    30

>> for i=[x';y']
disp(['size of i = ' num2str(size(i)) ', i(1) = ' num2str(i(1)) ', i(2) = ' num2str(i(2))])
end
size of i = 2  1, i(1) = 1, i(2) = 10
size of i = 2  1, i(1) = 2, i(2) = 20
size of i = 2  1, i(1) = 3, i(2) = 30
>> 
like image 105
mattiast Avatar answered Sep 30 '22 21:09

mattiast


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

dostuff = @(my_ten, my_one) my_ten + my_one;

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

x = arrayfun(dostuff, tens, ones);

x

Yields...

x =

   11   22   33
like image 23
DMC Avatar answered Sep 30 '22 20:09

DMC