3

I need to build up a vector of non-linear equations to be used in fsolve to solve it. But I should make each element of the vector in each loop iteration. How can I make up such a vector? In fact, I can not use cell array. How can I convert a cell array like {@(x) x(1)+x(2)^2; @(x) x(1)-2*(x(2))} into an array like @(x) [ x(1)+x(2)^2 ; x(1)-2*(x(2))]? Because I want to use fsolve to solve the system of non-linear equations.

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

2 Answers2

2

Use func2str to get the function definitions in string and use str2func to get the desired function, if A is the cell array containing the function handles:

B = strcat(regexprep(cellfun(@func2str, A, 'uni', 0), '^@\(x\)', ''), ';');
F = str2func(strcat('@(x) [', B{:}, ']'));

Now F contains the desired function handle.

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

Why convert? Why not use something like

% Your cell array
Fs = {@(x) x(1)+x(2)^2; @(x) x(1)-2*x(2)};

% Just use cellfun
solution = fsolve(@(y) cellfun(@(x) x(y), Fs), [0 0])
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
  • This should work, but then `cellfun` will be called for each evaluation and it has a performance penalty. – Mohsen Nosratinia Sep 04 '13 at 10:59
  • @MohsenNosratinia: true, but it comes at the benefit of being much simpler to implement and easier to modify when things change; your solution is specific to *this* particular problem, mine is more general. Also things like `@(~)` (for constants or so) are not parsed correctly. – Rody Oldenhuis Sep 04 '13 at 11:13