user2745742
user2745742

Reputation: 65

Matrix multiplication of a Array Cell of function handle

I have built up a cell array of function_ handles like below:

B = {@(x) x(1)+x(2)^2 
     @(x) x(1)-2*x(2)}

Assume A = [1 2; 3 4]. I need to perform a matrix multiplication like A*B to have a cell array as

A*B = {@(x) x(1)+x(2)^2 + 2*(x(1)-2*x(2)) 
       @(x) 3*(x(1)+x(2)^2) + 4*(x(1)-2*(x(2))} 

How can I do this?

Upvotes: 1

Views: 921

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38042

There is no way other than:

  1. writing your own class that supports multplications and/or additions of function_handles and doubles
  2. converting everything to string, manipulating the strings, and convert back to function handle (see the wonderful version Mohsen came up with)
  3. Do not actually create A*B but rather just evaluate it (just compute A*cellfun(@(f)f(y),B) for some y)
  4. Manually copy-pasting the expressions
  5. ...something else undoubtedly ugly.

Just out of curiosity, could you please explain why you 'need' this operation?

Upvotes: 0

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

It is relatively easy if you have access to Symbolic Toolbox:

C=regexprep(cellfun(@func2str, B, 'uni', 0), '@\(x\)', '');
F=arrayfun(@(d) ['@(x) ', char(d)], sym(A)*sym(C), 'uni', 0);

This returns

>> F
F = 
    '@(x) 3*x(1) - 4*x(2) + x(2)^2'
    '@(x) 7*x(1) - 8*x(2) + 3*x(2)^2'

Note that Symbolic manipulation actually simplies the result.

Upvotes: 1

Related Questions