How to create a loop on function handle
13 views (last 30 days)
I want to write the following in an efficent way using a loop over j = 1:n. A is n by n matrix, t(i) is a scalar (where i is another index, c is n by 1 vector, and f is a function handle. I want the output to be function handle XI which is an n by 1 vector and whose argument is the vector xi of length n by 1
Here n = 3, but I want it for general n.
A = ones(3,3);
c = ones(3,1);
f = @(t,y) t * y;
XI = @(xi) [xi - (y(i,:) + dt* A(:,1) .* f(t(i)+c(1)*dt,xi(1)) +...
dt* A(:,2) .* f(t(i)+c(2)*dt,xi(2)) +...
dt* A(:,3) .* f(t(i)+c(3)*dt,xi(3)))];
James Tursa on 24 Jun 2022
Edited: James Tursa on 24 Jun 2022
Isn't this just a standard matrix*vector multiply? E.g.,
XI = @(xi) xi - (y(i,:) + A*((t(i)+c*dt).*xi)*dt);
Note that this function handle will be pulling all the non-arguments A, y, i, t, and dt from the workspace at the time the function handle is created. I.e., it will take a shapshot of those variables and store them inside the function handle. I strongly suspect this isn't what you intended or wanted. To make the function handle responsive to changes in variables, you need to include those variables in the argument list. E.g.,
XI = @(xi,A,y,i,t,dt) xi - (y(i,:) + A*((t(i)+c*dt).*xi)*dt);
Now the function handle XI will be using the values of the variables passed into it for all the calculations, instead of just xi and past snapshots of the other variables as you have originally coded.