sonicboom
sonicboom

Reputation: 5028

How can I vectorize the function besselj(m,x) in Matlab where both m and x are are vectors?

I want to speed up the following code by vectorization:

b = zeros(3,5);
for m=1:3
    for x=1:5
        b(m,x) = besselj(m,x)
    end
end

That is, I want to calculate all values of besselj for m ranging over 1 to 3 and x ranging over 1 to 5.

Here is what I tried:

m=1:3;
x=1:5;
b = besselj(m,x)

I get the following error:

Error using besselj
NU and Z must be the same size or one must be a scalar.

So is it possible to use vectorization of both variables somehow or am I forced to only vectorize one of them and use a for loop for the other?

Upvotes: 1

Views: 169

Answers (2)

Adam
Adam

Reputation: 2777

Alternatively use meshgrid to compute all the possible pairing (m, x) before vectorizing

m = 1:3;
x = 1:5;

[X, M] = meshgrid(x,m);

b = besselj(M, X);

Upvotes: 4

Andreas H.
Andreas H.

Reputation: 6105

What about

x = 1:5
b = zeros(3,length(x));
for m=1:3
    b(m,:) = besselj(m,x);
end

So yes, you can only vectorize one of the arguments. But in my experience vectorizing along the "longer" axis is often sufficient.

Upvotes: 1

Related Questions