I am trying to run a loop which includes a function handle. The code works well if I use any specific value for n. However, when I try to run the code within a loop it gives the error:
Nonscalar arrays of function handles are not allowed; use cell
arrays instead.
I am relatively new to MATLAB, so after trying for a couple of hours I have run out of ideas... any help will be greatly appreciated.
The code is below
for m=1:N
for n=1:N
int(n) = @(w,s0,v,r,t) chfun_norm(s0,v,r,t,w(n)-(alpha+1)*1i)/(alpha^2 + alpha - w(n)^2 + 1i*(2*alpha+1)*w(n));
int(n) = @(w)int(w,s0,v,r,t);
g(n) = exp(1i*(b-log(s0))*w(n)-alpha*k(m)-r*t)*int(n)*pond(n);
g(n) = exp(-1i*2*pi/N*(n-1)*(m-1))*g(n);
end
y(m) = real(sum(g))*stepw;
end
EDIT
I have reformulated the loop using cell arrays, but I am now getting the following error
Undefined function 'mtimes' for input arguments of type 'function_handle'
Below is the updated code:
y = zeros(N,1);
intCell = {zeros(N,1)};
gCell = {zeros(N,1)};
for m=1:N
for n=1:N
intCell{n} = @(w,s0,v,r,t) chfun_norm(s0,v,r,t,w(n)-(alpha+1)*1i)/(alpha^2 + alpha - w(n)^2 + 1i*(2*alpha+1)*w(n));
intCell{n} = @(w)intCell{n}(w,s0,v,r,t);
gCell{n} = exp(1i*(b-log(s0))*w(n)-alpha*k(m)-r*t)*intCell{n}*pond(n);
gCell{n} = exp(-1i*2*pi/N*(n-1)*(m-1))*g(n);
end
y(m) = real(sum(g))*stepw;
end
The error message tells you exactly what to do. Without looking at what your code actually does, a non-scalar array (your int) cannot hold function handles. You have to put multiple function handles in a cell array. Those are capable to hold different and mixed types of data. int therefore needs to be a cell array.
Just read up on how to use cell arrays in Matlab.
On an unrelated note, in languages with stronger typing int may be a type, to prevent confusion it may be reasonable to change that variable's name.
Edit
The 2nd error is probably caused by the last multiplication(s) in line 8. You are trying to multiply a function handle. I suppose that you want to multiply with the return value of said function? If so, the function referenced by the handle stored in intCell still needs parameters to execute, like in lines 6 and 7.