1

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?

Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
user2745742
  • 65
  • 1
  • 4

2 Answers2

1

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.

Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
0

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?

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
  • You know i am going to solve a system of nonlinear equations AB(X) = X. X={x1,x2,...,xn} is a vector of n-dim and B(X) is a vector of the same dim holding in each of its row a nonlinear equation in terms of the {x1,x2,...,xn} and A is a nxn matrix of constant values. The point is that each row of B(X) is formed through the program in a FOR loop. I want to use fsolve to solve the set of equations. – user2745742 Sep 04 '13 at 13:46
  • @user2745742: that doesn't really justify this technique. You are basically solving a linear combination of nonlinear equations. There are better ways to do that (gotta run now, sorry) – Rody Oldenhuis Sep 04 '13 at 14:09
  • I implemented your solution 5) below :) – Bas Swinckels Sep 04 '13 at 18:18