-1

This is a python code. I want to convert this code into MATLAB and 'for' loop in one line but I can't.

calibration = {'rms': result[0], 'camera_matrix': result[1].tolist(), 'dist_coefs':result[2].tolist(), 'rotational_vectors': {("image" + str(c)): x.tolist() for c, x in enumerate(result[3])},'translational_vectors': {("image" + str(c)): x.tolist() for c, x in enumerate(result[4])},'image_files_names': [[c, x] for c, x in enumerate(imageFileNames)]}

  • 2
    Does this answer your question? [Matlab equivalent of Python enumerate](https://stackoverflow.com/questions/25469168/matlab-equivalent-of-python-enumerate) – DarrylG Jul 18 '21 at 08:22

1 Answers1

1

Unfortunately, while I learned MATLAB, I don't remember any function similar to enumerate() in Python for MATLAB

Maybe you can define your own function enumerate and use it as and when you want by defining it earlier on simply creating a custom package (toolbox)

Here's how I would create an enumerate() function for MATLAB:

classdef enumerate < handle
   properties(Access = private)
      IterationList;
   end
   
   methods 
       function self = enumerate(in)
           self.IterationList = in;
       end
       function [varargout] = subsref(self, S)
           item = subsref(self.IterationList,S);
           num = S.subs{2};
           out.item = item;
           out.num = num;
           varargout = {out};
       end
       function [m,n] = size(self)
           [m,n] = size(self.IterationList);
       end
   end
end

Once defined, simply use it to your liking like:

for t = enumerate(linspace(0,1,10));
disp(['Number: ',num2str(t.num),'Item: ',num2str(t.item)]); 
end

How to create a MATLAB Custom Toolbox Check this

Alternatively if you have a 1D Array:

enumerate = @(values) [1:length(values); values]

a = [6 5 4]
for i=enumerate(a)
    do something with i
end

Also there's some documentation about enumerations for MATAB r2021a https://www.mathworks.com/help/matlab/enumeration-classes.html

Additional sources: https://www.mathworks.com/help/matlab/matlab_prog/access-data-in-a-cell-array.html

aryashah2k
  • 638
  • 1
  • 4
  • 16
  • 1
    This is really nice! Your link to enumeration classes is unrelated though. That’s a way to give a name to a series of numbers, equivalent to Python [`enum`](https://docs.python.org/3/library/enum.html). – Cris Luengo Jul 18 '21 at 14:02
  • Indeed @CrisLuengo, realized it later on...! – aryashah2k Jul 18 '21 at 17:09