Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the equivalent of the Python zip function in MATLAB?

I have a Python code below that will zip through two arrays and print the output. What would the equivalent of this code be in MATLAB?

x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]

for i, j in zip(x, y):
    print(i, j)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There are two things you can do.

The most natural method in MATLAB is iterating over the index:

x = [1, 2, 3, 4, 5];
y = [10, 20, 30, 40, 50];

for i = 1:numel(x)
   disp([x(i), y(i)]);
end

The alternative is to concatenate the two arrays. MATLAB’s for loop iterates over the columns of the array:

for i = [x;y]
   disp(i.');
end

Note that this alternative is typically much less efficient, because concatenation requires copying all the data.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading