Help with fzero equation solver

3 views (last 30 days)
James
James on 20 Jun 2013
I have a equation with 3 variables A,B,C and want to know for each A,B combination the value of C that makes the equation equal to zero.
The fzero function seems the best way to do this.
The code is like this (slight simplification to actual fun):
A=[0:1:10];
B=[0:1:10];
fun=C+(0.5.*(A+B));
C=fzero(fun)
I have looked at the mathworks help on fzero but can't get it to work.
I get the error that 'C' is unknown but that's what I'm trying to find!

Answers (2)

Tom
Tom on 20 Jun 2013
There are a couple of things here: fzero only works with scalars, so you can't use it on all A and B values.
Secondly, you need to create a function handle to the function, using the @ sign.
So in your case, this is:
fun=@(C) C+(0.5.*(A+B));
Now using A = 10, B = 10 as an example
C=fzero(fun,0)
C =
-10
  1 Comment
James
James on 20 Jun 2013
OK thanks Tom. It's now working for a specified A,B pair of values.
The best way to get all values would be to put this code inside two for loops? Like this:
A=[1:1:10];
B=[1:1:10];
ansmatrix=zeros(length(A),length(B));
for a=1:length(A)
for b=1:length(B)
fun=@(C) C+(0.5.*(A(a)+B(b)));
C=fzero(fun,0);
ansmatrix(a,b)=C;
end
end
Or is there a better way without this for loops method?

Sign in to comment.


Tom
Tom on 20 Jun 2013
There is a way to do this without a loop:
You have one unknown (C) and one equation (fun), and you are looking for
C + f(A,B) = 0
Therefore,
C = -f(A,B)
So now you can use BSXFUN to run the function using all the combinations of A and B:
fun=@(x,y) -(0.5.*(x+y));
bsxfun(fun,A,B')

Tags

Community Treasure Hunt

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

Start Hunting!