Dimension issues when using fsolve
조회 수: 3 (최근 30일)
이전 댓글 표시
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
Ning Wu
2015년 9월 22일
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]
답변 (3개)
Titus Edelhofer
2011년 11월 25일
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
Titus Edelhofer
2011년 11월 25일
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
2011년 11월 25일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Linear Programming and Mixed-Integer Linear Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!