简体   繁体   English

在循环中将输出添加到匿名函数

[英]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. 我想在for循环的每一步中添加一个方程,而不是在创建函数时定义所有方程。 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”中包含的内容,

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. 不必担心显示“ ii”而不是我们之前给出的循环变量的实际数量,MATLAB在内部用这些值替换了它们。 Changing 'ii' in the current function scope will also not affect their values in 'A' either. 在当前函数范围内更改“ ii”也不会影响其在“ A”中的值。

Thus, A{1}(2) = 5 , A{2}(2) = 6 and A{3}(2) = 7 因此, A{1}(2) = 5A{2}(2) = 6A{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. 希望这对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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