Matlab - 匿名函数中的for循环
我对 matlab 很陌生,但我知道如何执行 for 循环和匿名函数。现在我想把这些结合起来。
我想写:
sa = @(c) for i = 1:numel(biscs{c}),figure(i),imshow(biscs{c}{i}.Image),end;
但这是无效的,因为 matlab 似乎只希望换行符作为命令分隔符。我以清晰的方式编写的代码是(没有函数头):
for i = 1:numel(biscs{c})
figure(i)
imshow(biscs{c}{i}.Image)
end
我寻找一种解决方案,可以像我的第一个示例一样在一行中使用匿名函数编写它。如果我能以另一种方式创建该函数,只要我不需要新的函数 m 文件,我也会很高兴。
I'm quite new to matlab, but I know how to do both for loops and anonymous functions. Now I would like to combine these.
I want to write:
sa = @(c) for i = 1:numel(biscs{c}), figure(i), imshow(biscs{c}{i}.Image), end;
But that isn't valid, since matlab seem to want newlines as only command-seperator. My code written in a clear way would be (without function header):
for i = 1:numel(biscs{c})
figure(i)
imshow(biscs{c}{i}.Image)
end
I look for a solution where either I can write it with an anonymous function in a single line like my first example. I would also be happy if I could create that function another way, as long as I don't need a new function m-file for i.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
匿名函数可以包含多个语句,但不能包含显式循环或 if 子句。多个语句在元胞数组中传递,并依次进行计算。例如,此函数将打开一个图形并绘制一些数据:
但是,这并不能解决循环问题。幸运的是,有ARRAYFUN。这样,您就可以如下编写循环:
方便的是,该函数还返回
figure
和imshow
的输出,即各自的句柄。Anonymous functions can contain multiple statements, but no explicit loops or if-clauses. The multiple statements are passed in a cell array, and are evaluated one after another. For example this function will open a figure and plot some data:
This doesn't solve the problem of the loop, however. Fortunately, there is ARRAYFUN. With this, you can write your loop as follows:
Conveniently, this function also returns the outputs of
figure
andimshow
, i.e. the respective handles.如果您从另一个函数调用此函数,则可以在主函数的 .m 文件末尾定义它,然后使用 @name 语法引用它。但这不适用于脚本文件,因为它们不能包含子函数。
第二种方法有点脏,但仍然可行,并且是使用 eval STRING:
如果脚本文件能够以某种方式允许子函数的定义,那就太好了,但这不太可能。
If you're calling this function from another function, you can define it at the end of the main function's .m file, then refer to it using the @name syntax. This doesn't work from script files, though, as these cannot contain sub functions.
A second approach is somewhat dirty, but nevertheless might work, and is to use eval STRING:
It would be great if script files could allow the definition of sub functions somehow, but this is unlikely.