Matlab-匿名函数中的for循环 [英] Matlab - for loop in anonymus function

查看:720
本文介绍了Matlab-匿名函数中的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Matlab还是很陌生,但是我知道如何同时执行循环和匿名函数.现在,我想将这些结合起来.

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)

方便地,此函数还返回figureimshow的输出,即相应的句柄.

Conveniently, this function also returns the outputs of figure and imshow, i.e. the respective handles.

这篇关于Matlab-匿名函数中的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆