How to pass vectors as arguments for functions created using str2func ?

f=str2func('@(x,y,z) x+y+z');
w=[1,1,1];
y=f(w) % want to compute f(1,1,1) using vector x
This gives an error when I tried to compute y
Thanks in Advance for your help !!

5 Comments

% want to compute f(1,1,1) using vector x
The problem is that f(1,1,1) is NOT one vector, but three independent input arguments to f. Confusion about very basic MATLAB concepts like this is best helped by doing the introductory tutorials (which are highly recommended for all beginners):
And in particular this section:
To add a simple logic: you have defined x but not y and z as inputs ...
In my problem, number of independent input arguments to f is variable and therefore I want to use an array(or vector) of variable size to compute f.
Also I mistakely wrote the same variable name 'x' for vector and 'x' as a variable of f. I have corrected it now.
f= @(w) sum(w);
w=[1,1,1];
y=f(w)
would do what you ask. str2func just obfuscates what you are doing by adding an extra un-needed layer.
If you want to do something more complicated than a sum on a vector input though that is complicated in an anonymous function like that given variable input lengths.
I actually want to solve N simultaneous equation(not necessarily linear) with N variables(which I am taking as input from a text file) using Newton Raphson method.
I have stored these equations in N dimension string. Now I am converting the strings to functions and therefore I am using str2func.
Kindly suggest if you have a better method to solve it.

Sign in to comment.

 Accepted Answer

It has nothing to do with str2func. You need to define the function differently,
f=str2func('@(x) sum(x)');
or
f=str2func('@(x) x(1)+x(2)+x(3)');

1 Comment

I actually want to solve N simultaneous equation(not necessarily linear) with N variables(which I am taking as input from a text file) using Newton Raphson method.
I have stored these equations in N dimension string. Now I am converting the strings to functions and therefore I am using str2func.
I think if I use x(1), x(2),x(3).... as variables instead of x,y,z.., the problem will be solved.
Thanks for the answer. Kindly suggest if you have a better method to solve it.

Sign in to comment.

More Answers (0)

Categories

Find more on Parallel Computing in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!