2

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)
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Logan
  • 31
  • 6
  • "Pro tip" - you already got answers, but for future's sake, it is helpful if you added a example of the expected output of that Python code. – ysap Aug 15 '22 at 10:41

3 Answers3

2

You can iterate through the index, matlab likes for loop.

matlab
for i=1:5
   x(i), y(i)
end
Only god knows
  • 307
  • 1
  • 10
2

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.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
2

For MATLAB, there is no equivalent for the python zip function; if you were looking for something like that, I would recommend checking out this SO answer about creating a zip function in MATLAB.

Otherwise, iterating through indices works.

% Create lists
x = [1 2 3 4 5];
y = [1 2 3 4 5];

% Assuming lists are same length, iterate through indices
for i = 1:length(x)
    disp([x(i) y(i)]);
end
ndhulipala
  • 112
  • 6