Matlab - for loop in anonymus function

╄→尐↘猪︶ㄣ 提交于 2019-12-04 00:34:07

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.

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.

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