1

This is simplified but take as an example the following MATLAB function handle:

F = @(x)[x(1)-x(2);x(2)-x(3)]

The system has of course has many solutions. Is it possible to obtain a solution for a function like this one after substituting at least one variable? For example, substituting x(3)=1 the function would become:

G = @(x)[x(1)-x(2);x(2)-1]

And a solution for the other variables can be obtained. I use fsolve and it works quite well for the system of equations I have. Of course what I need to do can be done using the Symbolic Toolbox, but calling it in a big for loop makes it too slow to use for my code.

I'm trying to come up with some code that can return G given F and a set of indices in x to replace with given values.

gnovice
  • 125,304
  • 15
  • 256
  • 359
ser
  • 13
  • 3
  • 1
    Possible duplicate of [Convert input of an anonymous function](https://stackoverflow.com/questions/47486471/convert-input-of-an-anonymous-function) – Sardar Usama Nov 27 '17 at 16:57
  • Nice example. Almost what I need to do. The difference is that to evaluate F I use x, which is a vector. Can this be done with vectors? Think of the following function: `function G = convert (F, x, xMatrix)` Where xMatrix states which variables are to be substituted. For example if x=[3,2,1] and xMatrix=[0,0,1] that means G will be `G = @(x)[x(1)-x(2);x(2)-1]` Can this be done? – ser Nov 27 '17 at 22:31
  • @SardarUsama: It's more complicated than that, since it's replacing indexed elements in the argument as opposed to replacing an entire input argument. – gnovice Nov 28 '17 at 19:59

1 Answers1

0

What you're basically asking to do is have G call F with values in x reassigned based on a logical replacement index index and a set of replacement values values, which is doable but messy since anonymous functions can only have a single executable statement.

The solution is similar to what is done in this answer, but instead of using the functional form for subscripted reference we'll need to use the functional form for subscripted assignment: subsasgn. Here's what it would look like:

F = @(x)[x(1)-x(2); x(2)-x(3)];
values = [3 2 1];
index = logical([0 0 1]);
G = @(x) F(subsasgn(x, struct('type', '()', 'subs', {{index}}), values(index)));

And here's a test:

>> F([3 2 3])

ans =

     1
    -1

>> F([3 2 1])  % Replace the last element by 1

ans =

     1
     1

>> G([3 2 3])  % G handles replacing the last element by 1

ans =

     1
     1
gnovice
  • 125,304
  • 15
  • 256
  • 359
  • This work perfectly. It is fast and fsolve doesn't solve for the substituted values, which is exactly what I needed. Might be messy (it's not easy to understand) but it looks efficient. Great programming skills! Million thanks. – ser Nov 28 '17 at 22:14
  • @ser: Happy to help! Don't forget you can [mark answers as accepted](https://stackoverflow.com/help/accepted-answer). – gnovice Nov 28 '17 at 22:23