patternMinor
Vectorize Matlab sum
Viewed 0 times
vectorizematlabsum
Problem
I have the following Matlab function:
It's emulating this equation:
\$f(x) = \sum_{i=1}^{n}|x_i|^{i+1}\$
Here is an example use:
I know I should be able to use the
function [res] = a3_funct(x)
res = 0;
for i = 1:size(x,1)
res = res + abs(x(i))^(i+1);
end
endIt'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 =
90I know I should be able to use the
sum() function to make this faster, but how do I get the exponents in there?Solution
Vectorized approach:
Read more about vectorization techniques here.
Thus, your function would look like this:
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)));
returnCode Snippets
res = sum(abs(x(:).'.^(2:numel(x)+1)))function res = a3_funct(x)
res = sum(abs(x(:).'.^(2:numel(x)+1)));
returnContext
StackExchange Code Review Q#55236, answer score: 7
Revisions (0)
No revisions yet.