The error message give you a big hint where to look:
Undefined operator ‘+’ for input arguments of type ‘cell’.
Error in gbp2/pts (line 36)
ylist(z) = ylist(z) + arrayfun(@(coor) u(z, coor, mode, w, R,
Psi),xlist(z).’,’uniformoutput’,false);
From the documentation for arrayfun
and the 'UniformOutput'
option:
Requests that the arrayfun function combine the outputs into cell arrays B1,…,Bm. The outputs of function func can be of any size or type.
Indeed, if you check, the output of this line is a cell array:
arrayfun(@(coor) u(z, coor, mode, w, R, Psi),xlist(z),'uniformoutput',false)
You can’t sum the values from the cell array directly. Here’s one of several ways you can do this:
v = arrayfun(@(coor) u(z, coor, mode, w, R, Psi),xlist(z),'uniformoutput',false);
ylist(z) = ylist(z) + [v{:}];
However, I don’t see why you need to used the 'UniformOutput'
option or even the slow arrayfun
at all. Just vectorize your function with respect to coor
:
u = @(z, coor, mode, w, R, Psi)(2/pi)^(1/4)*sqrt(exp(1i*(2*mode+1)*Psi)/(2^mode*factorial(mode)*w))*...
hermiteH(mode,sqrt(2)*coor/w).*exp(-coor.^2*(1/w^2+1i*k/(2*R))-1i*k*z);
Now
ylist(z) = ylist(z) + u(z, xlist(z), mode, w, R, Psi);
Some additional suggestions: Don’t use global
variables – they’re inefficient and there are almost always better solutions. If pts
is meant to be a nested function, you’re missing a closing end
for the main gbp2
function. It might be a good idea to rename your variable mode
so that it doesn’t overload the built-in function of the same name. Psif
isn’t defined. And zeros(1,size(xlist(z),2))
can be written simply as zeros(size(xlist(z)))
.
5
solved Non-scalar in Uniform output error in arrayfun. How to fix?