简体   繁体   中英

Is there any similar function in MATLAB like enumerate()

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)]}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM