speed for loop in sum

Can the for loop be removed ?
x=linspace(-2,2,100); %some vector
[X,XX]=meshgrid(x,x); %some matrix
a=1/2;%some constant
A0=zeros(size(X));%initialize the sum
A0k = @(k,X,a)(((-1)^k).*((X./a).^(2*k)).*besselj(2*k,X));%series
for l=0:20
A0 = A0+A0k(l,X,a); %sum of series
end

2 Comments

Torsten
Torsten on 11 Mar 2019
Edited: Torsten on 11 Mar 2019
What's the problem with the solution I gave ?
Ole
Ole on 11 Mar 2019
I was not able to make it work.

Sign in to comment.

 Accepted Answer

Torsten
Torsten on 11 Mar 2019

1 vote

function main
x = linspace(-2,2,100); %some vector
[X,XX] = meshgrid(x,x); %some matrix
k = 0:20;
a = 0.5;
A0 = arrayfun(@(x)sum((-1).^k.*(x/a).^(2*k).*besselj(2*k,x)),X)
end

1 Comment

Ole
Ole on 11 Mar 2019
Thank you!
just as feedback the arrayfun is slower than the loop.
0.096s for the for loop
0.30s for the arrayfun

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Asked:

Ole
on 11 Mar 2019

Commented:

Ole
on 11 Mar 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!