Dimension issues when using fsolve
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hello everyone, I face some "dimension issues" when using fsolve. Thus, I tried to use the exact example in the matlab help: http://www.mathworks.fr/help/toolbox/optim/ug/fsolve.html (example 1). Following the example, my initial condition is always given by:
x0 = [-5; -5];
After playing around a bit, I discovered that when I put the function F as follows:
F = [2*x(1) - x(2) - exp(-x(1)); -x(1) +2*x(2) - exp(-x(2))];
I get the error message: ??? Error using ==> vertcat CAT arguments dimensions are not consistent.
When I type:
F = [2*x(1) - x(2) - exp(-x(1)); -x(1) + 2*x(2) - exp(-x(2))];
it works! The difference? In the second case, there is a space between the "+" and 2*x(2). First, I do not understand why these two ways of typing F should be any different. Second, it seems that fsolve is sensitive to dimensions. What should I be careful of when using it?
Thanks a lot!
Kyriacos
1 Kommentar
Ning Wu
am 22 Sep. 2015
I had the same problem when using fsolve. Titus is correct on this. To avoid this problem, just set tp1=2*x(1) - x(2) - exp(-x(1)); tp2=-x(1) +2*x(2) - exp(-x(2)); and write F=[tp1;tp2]
Antworten (3)
Titus Edelhofer
am 25 Nov. 2011
Hi Kyriacos,
if you leave out the first half of F you see the difference:
F = [-x(1) +2*x(2) - exp(-x(2))]
F =
5.0000 -158.4132
F = [-x(1) + 2*x(2) - exp(-x(2))]
F =
-153.4132
In the first case the + is interpreted as a unary plus (like if you write -2).Therefore you get the error because you can't combine one number and a vector of length 2 into a matrix.
Titus
1 Kommentar
Titus Edelhofer
am 25 Nov. 2011
Forgot to mention: although generally speaking spaces make code easier to read, this is a good example of being careful to use spaces in expressions using [], because space works as column separator.
Titus Edelhofer
am 25 Nov. 2011
Hi Kyriacos,
unary plus is similar to unary minus: instead of
x = 42.0;
you can just as well write
x = +42.0;
Having said this, MATLAB interprets
F = [2.0 +3.0]
equally to
F = [2.0 3.0]
instead of (what you wanted to have)
F = [2.0+3.0]
My recommendation for making your code somewhat more robust and easier to read: seperate the individual functions
f = zeros(21, 1);
f(1) = x(13) - 1;
f(2) = x(2) - x(8) - x(9);
f(3) = x(3) - x(6);
...
or (doing basically the same):
f1 = x(13) - 1;
f2 = x(2) - x(8) - x(9);
f3 = x(3) - x(6);
...
f = [f1; f2; f3; ...]
Hope this helps,
Titus
0 Kommentare
Siehe auch
Kategorien
Mehr zu Linear Programming and Mixed-Integer Linear Programming finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!