如何在MATLAB匿名函数中执行多个语句

如何在MATLAB匿名函数中执行多个语句

本文介绍了如何在MATLAB匿名函数中执行多个语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

 >所以,当我说:



 >> foo()

它会执行 functionCall1()然后执行 functionCall2()。 (我认为我需要类似)



编辑:



functionCall1 functionCall2 不一定是返回值的函数。

解决方案

命令行不保存m文件中的函数可能是一个复杂和杂乱的努力,但这里有一种方式我想出了...



首先,使你的,并将他们的 matlab_prog / br04bw6-98.htmlrel =nofollow noreferrer>单元格数组:

  fcn1 = @ )...; 
fcn2 = @()...;
fcn3 = @()...;
fcnArray = {fcn1 fcn2 fcn3};

...或者,如果你已经定义了函数单元格数组中的函数句柄如下:

  fcnArray = {@ fcn1 @ fcn2 @ fcn3} 

然后你可以创建一个新的匿名函数,使用内置函数调用数组中的每个函数和:

  foo = @()cellfun(@ feval,fcnArray); 

虽然很有趣,但是有效。



EDIT:如果 fcnArray 中的函数需要使用输入参数调用,那么首先必须确保所有函数该阵列需要相同数量的输入。在这种情况下,下面的示例显示如何调用每个都有一个输入参数的函数数组:

  foo = @ )cellfun(@ feval,fcnArray,x); 
inArgs = {1'a'[1 2 3]};
foo(inArgs); %#将1传递到fcn1,'a'到fcn2和[1 2 3]到fcn3



警告字词:说明其中计算输出元素的顺序未指定,不应被依赖。这意味着不能保证 fcn1 fcn2 fcn3 。如果订单重要,不应使用上述解决方案。


I'd like to do something like this:

>> foo = @() functionCall1() functionCall2()

So that when I said:

>> foo()

It would execute functionCall1() and then execute functionCall2(). (I feel that I need something like the C , operator)

EDIT:

functionCall1 and functionCall2 are not necessarily functions that return values.

解决方案

Trying to do everything via the command line without saving functions in m-files may be a complicated and messy endeavor, but here's one way I came up with...

First, make your anonymous functions and put their handles in a cell array:

fcn1 = @() ...;
fcn2 = @() ...;
fcn3 = @() ...;
fcnArray = {fcn1 fcn2 fcn3};

...or, if you have functions already defined (like in m-files), place the function handles in a cell array like so:

fcnArray = {@fcn1 @fcn2 @fcn3};

Then you can make a new anonymous function that calls each function in the array using the built-in functions CELLFUN and FEVAL:

foo = @() cellfun(@feval,fcnArray);

Although funny-looking, it works.

EDIT: If the functions in fcnArray need to be called with input arguments, you would first have to make sure that ALL of the functions in the array require THE SAME number of inputs. In that case, the following example shows how to call the array of functions with one input argument each:

foo = @(x) cellfun(@feval,fcnArray,x);
inArgs = {1 'a' [1 2 3]};
foo(inArgs);  %# Passes 1 to fcn1, 'a' to fcn2, and [1 2 3] to fcn3


WORD OF WARNING: The documentation for CELLFUN states that the order in which the output elements are computed is not specified and should not be relied upon. This means that there are no guarantees that fcn1 gets evaluated before fcn2 or fcn3. If order matters, the above solution shouldn't be used.

这篇关于如何在MATLAB匿名函数中执行多个语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 04:00