Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have the following Matlab function:

function [res] = a3_funct(x)
    res = 0;
    for i = 1:size(x,1)
        res = res + abs(x(i))^(i+1);
    end
end

It's emulating this equation:

\$f(x) = \sum_{i=1}^{n}|x_i|^{i+1}\$

Here is an example use:

>> a3_funct([1,2,3]')

ans =

    90

I know I should be able to use the sum() function to make this faster, but how do I get the exponents in there?

share|improve this question
    
In Revs 1–4, your equation was inconsistent with your code. Your code actually does $$f(x) = \sum_{i=1}^{n}\left|x_i\right|^i$$ if you use one-based arrays, according to MATLAB convention, or $$f(x) = \sum_{i=0}^{n-1}\left|x_i\right|^{i + 1}$$ if you use the zero-based array indexing convention. –  200_success Jun 29 '14 at 22:25
    
@200_success fixed it –  Seanny123 Jun 29 '14 at 22:56

1 Answer 1

up vote 6 down vote accepted

Vectorized approach:

res = sum(abs(x(:).'.^(2:numel(x)+1)))

Read more about vectorization techniques here.

Thus, your function would look like this:

function res = a3_funct(x)
    res = sum(abs(x(:).'.^(2:numel(x)+1)));
return
share|improve this answer
    
Feel free to flag a question for moderator attention if the code in a question doesn't work as advertised. –  200_success Jun 29 '14 at 23:02
    
@200_success Thank you! Would keep that in mind. –  Divakar Jun 30 '14 at 3:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.