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?
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);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.