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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With