Matlab - for loop in anonymus function

北慕城南 提交于 2019-12-05 13:51:15

问题


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.


回答1:


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)}

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)

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




回答2:


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:

fun = @(a,b) eval('for i = 1:a; imshow(b(i)); end');

It would be great if script files could allow the definition of sub functions somehow, but this is unlikely.



来源:https://stackoverflow.com/questions/5660660/matlab-for-loop-in-anonymus-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!