MATLAB Answers

How can I multiply each element of a cell array, defined as an anonymous function handle?

16 views (last 30 days)
I have a cell array FS which contains a function handle at each cell. I want to multiply the output of each cell with each other (giving each function handle the SAME input). The function handles in each cell are identical except for the i value stored in them.
Define array as:
N = 5;
for i=1:N
FS{i} = @(x) x+i;
end
i can obtain my desired result by a simple loop:
x = 3;
P = FS{1}(x)
for i=2:length(FS)
P = P * FS{i}(x)
end
However, I wish to define this operation as a new function handle, performing the same action:
b = @(x) FS{1}(x) * FS{2}(x) * FS{3}(x) ... * FS{N}(x)
but this should of course be flexible for any number of elements (FS).

  0 Comments

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 26 Sep 2018
b = @(x) prod(cellfun(@(F) F(x), FS))
This assumes that the output of each handle is scalar even if x is non-scalar.
If you really do mean * as in algebraic matrix multiplication, which assumes that the results of each function handle will be either a scalar or a matrix whose number of columns is the same as the number of rows of output of the next function handle (e.g., square matrices work well) then
b = @(x) fold(@mtimes, cellfun(@(F) F(x), FS), 1);

  9 Comments

Show 6 older comments
Jonas Holfelt
Jonas Holfelt on 27 Sep 2018
Thanks. I ended up making a function like that, defined as:
function cascadedOut = cascadeCells(fcellArray,F)
cascadedOut = fcellArray{1}(F);
for i=2:length(fcellArray)
cascadedOut = cascadedOut * fcellArray{i}(F);
end
end
This worked!
Georgios Koutsakis
Georgios Koutsakis on 4 Oct 2019
Hi, interesting approach.
Could you please share the final working version of the code?
I tried to replicate it from by end, but something doesn't seem quite right.
Thanks

Sign in to comment.

More Answers (0)

Sign in to answer this question.