Help with fzero equation solver

6 ビュー (過去 30 日間)
James
James 2013 年 6 月 20 日
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!

回答 (2 件)

Tom
Tom 2013 年 6 月 20 日
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 件のコメント
James
James 2013 年 6 月 20 日
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?

サインインしてコメントする。


Tom
Tom 2013 年 6 月 20 日
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')

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by