matlabfor-loopsum

Is there a more elegant way to write sum in MATLAB code


disto_pow = spectral_pow(h_idx * 2) + spectral_pow(h_idx * 3) + spectral_pow(h_idx * 4) + spectral_pow(h_idx * 5) + spectral_pow(h_idx * 6);

spectral_pow is an array and h_idx is a scalar.

Is there a more elegant way to write this sum in a single line? Even the sum() function is pretty lengthy and a for loop seems very exorbitant/more for just a sum.

No issues or bugs in script as of now but just want to know.


Solution

  • To get the array values at multiples of the scalar index h_idx, you can do so in a single command

    spectral_pow(h_idx*(2:6));
    

    Since h_idx*(2:6) gives the array of indices you want.

    Then the sum of this array gives you your output

    disto_pow = sum( spectral_pow(h_idx*(2:6)) );