Buzz92
Buzz92

Reputation: 9

Take product of function handles within a cell and then evaluate for given values in MATLAB

I have a cell of function handles and I would like to take the product of each row.

I then want to evaluate the function handles within the cell for certain values.

Example:

Original cell:

P{1,1} = @(x) x         P{1,2} = @(y) y
P{2,1} = @(x) x         P{2,2} = @(y) y.^2

Desired product:

P{1,1} = @(x,y) x.*y
P{2,1} = @(x,y) x.*y.`2

Then evaluate for

x = 2:0.1:3;
y = 1:0.1:2;

Then I suppose use cell2mat to get P?

I have been trying to use cellfun, but not sure if this is correct when using anonymous functions.

Would appreciate any advice!

Upvotes: 0

Views: 50

Answers (1)

rahnema1
rahnema1

Reputation: 15867

You can reshape input vectors x , y to 3D vectors and apply the function on them:

P{1,1} = @(x) x ;        P{1,2} = @(y) y;
P{2,1} = @(x) x  ;       P{2,2} = @(y) y.^2;
%reshape input to 3D
x=reshape(2:0.1:3,1,1,[]);
y=reshape(1:0.1:2,1,1,[]);
%empty cell of results
C = cell(size(P));
%apply functions of each column to the related input
C(:,1) = cellfun(@(f)f(x),P(:,1),'UniformOutput', false);
C(:,2) = cellfun(@(f)f(y),P(:,2),'UniformOutput', false);
%convert cell to an array
A = cell2mat(C);
%take product of each row
rowprod = prod(S,2)
%remove singleton dimensions
out = squeeze(rowprod)

Upvotes: 0

Related Questions