1

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
1
  • 1
    If find this question hard to answer, without knowing what this code is supposed to do. Potentially, that task can be achieved without a nested loop, but not all nested loops can be eliminated. Commented May 14, 2013 at 16:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.