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?
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
>>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With