Edwin Lu
Edwin Lu

Reputation: 13

Optimizing matlab code by removing nested for loop?

This is the code I was given, however it takes too long to run. How would I make this faster by removing the nested for loop?

    for iGroup = 1:length(groupIndices)
            curGroupIndex = groupIndices(iGroup);
            curChanIndices = chanIndices{iGroup};
            curChanNames   = chanNames{iGroup};

            groupPropStruct = propsToStruct(propNames{curGroupIndex},propValues{curGroupIndex},REPLACE_STR,PREPEND_STR,ALWAYS_PREPEND);
            groupStruct = struct('name',groupNames(iGroup),'props',groupPropStruct);
            for iChan = 1:length(curChanIndices)
                curChanIndex = curChanIndices(iChan);
                chanPropStruct = propsToStruct(propNames{curChanIndex},propValues{curChanIndex},REPLACE_STR,PREPEND_STR,ALWAYS_PREPEND);
                chanStruct =  struct('name',curChanNames{iChan},'props',chanPropStruct,...
                    'data',[]);
                chanStruct.data = data{curChanIndex};
                groupStruct.(TDMS_genvarname2(chanStruct.name,...
                    REPLACE_STR,PREPEND_STR,ALWAYS_PREPEND)) = chanStruct;
            end
            output.(TDMS_genvarname2(groupStruct.name,...
                REPLACE_STR,PREPEND_STR,ALWAYS_PREPEND)) = groupStruct;
        end

Upvotes: 1

Views: 105

Answers (1)

Tik0
Tik0

Reputation: 2699

As one said, it's hard to say without knowing, what your code is actual doing. Maybe you could give a toy-example regarding your code? This would help.

Anyway, here are four major points to consider, when writing MATLAB for-loops:

1: Of course, use build-in MATLAB functionality instead of for-loops. They are written in c/Fortran and are much faster regarding SIMD, multythreading, etc.

2: Your for-loops are consecutiv and look sliceable. Consider to use parfor loops, to use multi-processor functionality on the loop.

3: Is your for-loop capsuled in a matlab-function? If it is not, do it!, so that the yit-compiler from MATLAB can compile your loop to byte-code which is much faster!

4: If you are familiar with C++, write a mex-function. Here you can use the full potential of your machine.

Upvotes: 1

Related Questions