tags:

views:

40

answers:

1

I have a system of equations contained in an anonymous equation. Instead of defining all of the equations when i create the function, I would like to add one in each step of a for loop. Is this possible?

+3  A: 

I suppose if you have a linear set of equations, you can construct it using a matrix, then you're free to include new operations by adding rows and columns to the matrix and/or its accompanying right hand side vector.

If you're really trying to use anonymous functions, say if your functions are non-linear, then I would suggest you to look into arrays of anonymous functions. For example,

A = cell(3,1);          % Preallocate a 3 by 1 cell array
for ii = 1:3
  A{ii} = @(x) x^2+ii;  % Fill up the array with anonymous functions
end

Now if you check what's contained in cell array 'A',

A = @(x)x^2+ii
    @(x)x^2+ii
    @(x)x^2+ii

Don't worry about the display of 'ii' instead of the actual number of the loop variable as we gave it earlier, MATLAB has internally replaced them with those values. Changing 'ii' in the current function scope will also not affect their values in 'A' either.

Thus, A{1}(2) = 5, A{2}(2) = 6 and A{3}(2) = 7

If you're not familiar with cell arrays, you can read up on its usage here.

Again, what you're trying to achieve might be different. I hope this works for you.

dpwave

related questions