简体   繁体   中英

add outputs to anonymous function in loop

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM