How do I iteratively fill a large matrix within an anonymous function?

I am using Newton's Method for solving non-linear systems of equations in order to solve a complex set of partial differential equations. I have developed the method and applied it to a simpler problem with excellent results. In order to do this I defined the following anonymous functions and right-divided to solve the system of equations:
% Anonymous Functions
f=@(xsub)[xsub(1)/dt-Xsub(1,R)/dt-xsub(2);xsub(2)/dt-...
Xsub(2,R)/dt+g/L*xsub(1)];
% Newton's Method
Df=@(xsub)[1/dt,-1;g/L,1/dt];
xsub=Xsub(1:2,R);
This works very well. The only problem arises when I need to make much larger matrices (~5000x1 and ~5000x5000) for f and Df in the more complex problem. These clearly need to be filled iteratively but my attempts to do this have been unsuccessful. To further complicate the issue, the first and final rows of f and Df have different equations than the general rows. I have attempted to fill these larger matrices with for loops and if statements but I receive error messages related to assigning a cell value to a matrix. An example of my attempts to fill f with a for loop follows:
for i=1:2*N-2
f(i,1)=@(xsub) (expression containing xsub(i))
end
Any suggestions are appreciated.

 Accepted Answer

If your attempts at getting all of this logic into an anonymous function are becoming tedious and generating errors, it is time to rewrite this as a regular function and create a function handle that points to it. It will be easier to read and maintain.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!