Matlab - 匿名函数中的 for 循环 [英] Matlab - for loop in anonymus function
问题描述
我对 matlab 很陌生,但我知道如何同时使用 for 循环和匿名函数.现在我想把这些结合起来.
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.
我想写:
sa = @(c) for i = 1:numel(biscs{c}), figure(i), imshow(biscs{c}{i}.Image), end;
但那是无效的,因为 matlab 似乎只想要换行符作为命令分隔符.我以清晰的方式编写的代码将是(没有函数头):
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 新建一个函数 m 文件.
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.
推荐答案
匿名函数可以包含多个语句,但不能包含显式循环或 if 子句.多条语句在元胞数组中传递,并一个接一个地进行求值.例如,此函数将打开一个图形并绘制一些数据:
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:
fun = @(i,c){figure(i),imshow(imshow(biscs{c}{i}.Image)}
然而,这并不能解决循环的问题.幸运的是,有 ARRAYFUN.有了这个,您可以按如下方式编写循环:
This doesn't solve the problem of the loop, however. Fortunately, there is ARRAYFUN. With this, you can write your loop as follows:
sa = @(c)arrayfun(@(i){figure(i),imshow(biscs{c}{i}.Image)},...
1:numel(biscs{c}),'uniformOutput',false)
方便的是,该函数还返回figure
和imshow
的输出,即各自的句柄.
Conveniently, this function also returns the outputs of figure
and imshow
, i.e. the respective handles.
这篇关于Matlab - 匿名函数中的 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!