5
\$\begingroup\$

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?

asked Jun 25, 2014 at 16:05
\$\endgroup\$
0

1 Answer 1

7
\$\begingroup\$

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
200_success
145k22 gold badges190 silver badges478 bronze badges
answered Jun 25, 2014 at 16:45
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.