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

By : Jason
Source: Stackoverflow.com
Question!

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?

By : Jason


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
>> 
By : mattiast


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.

By : bastibe


This video can help you solving your question :)
By: admin