Suppose you have a loop with 50,000 iterations and you want to calculate averages (scalars) from many matrices. This is not complete, but something like this:
for k=1:50000 ... mean=sum(sum(matrix))/numel(matrix); %Arithmetic mean ... end
And now I want to include various mean equations to choose from. First I tried this:
average='arithmetic' for k=1:50000 ... switch average case 'arithmetic' mean=sum(sum(matrix))/numel(matrix); %Arithmetic mean case 'geometric' mean=prod(prod(matrix)).^(1/numel(matrix)); %Geometric mean case 'harmonic' mean=numel(matrix)/sum(sum(1./matrix)); %Harmonic mean end ... end
This is obviously much slower than the first loop, because it needs to find a matching string for each iteration, which seems completely unnecessary. Then I tried this:
average='arithmetic' switch average case 'arithmetic' eq=@ (arg)sum(sum(arg))/numel(arg); %Arithmetic mean case 'geometric' eq=@ (arg)prod(prod(arg)).^(1/numel(arg)); %Geometric mean case 'harmonic' eq=@ (arg)numel(arg)/sum(sum(1./arg)); %Harmonic mean end for k=1:50000 ... mean=eq(matrix); %Call mean equation ... end
This is about twice as slow as the first cycle, and I donβt understand why. The last two cycles are almost identical in speed.
Am I doing something wrong here? How can I achieve the same performance as the first loop with this extra feature?
Help is much appreciated!
shant source share