Solving dynamic system of equations with parameters

조회 수: 6 (최근 30일)
Sebastian
Sebastian 2014년 1월 15일
댓글: A Jenkins 2014년 1월 15일
Hello,
I would like to solve a system of equations with parameters. An example (with trivial math) is attached. The system and the variables I would like to solve it for are dependent on a user input. In my example that is the varialbe "length" which can take an arbitrary positive natural number.
I can solve it by explicitly listing the variables "a(1)", etc. in the solve function call. Since the varialbe vector "a" is userdependent I cant use that in general though.
The second function call to solve results in warnings and wrong answers, because solve assumes that the second input "a" is an equation array and not the variables to be solved for.
Any suggestions to solve the system for, say, a random (positive and natural number) "length"?
Thanks a lot in advance!
length = 3;
a = sym('a', [length, 1]);
equations = sym('something', [length, 1]);
syms p
for runIdx = 1:length
equations(runIdx) = a(runIdx) - p == 0;
end
answers_correct_but_static = solve(equations, a(1), a(2), a(3))
answers_incorrect_dynamic = solve(equations, a)

채택된 답변

A Jenkins
A Jenkins 2014년 1월 15일
Due to the way solve choses the variables to solve for ( symvar ), you may not need to specify the variables at all. For example, if you use 'x' as your variable name instead of 'a', this works in 2013b:
length = 3;
x = sym('x', [length, 1]);
equations = sym('something', [length, 1]);
syms p
for runIdx = 1:length
equations(runIdx) = x(runIdx) - p == 0;
end
answers_correct_dynamic = solve(equations)
  댓글 수: 2
Sebastian
Sebastian 2014년 1월 15일
편집: Sebastian 2014년 1월 15일
Hugh. Your suggestion works indeed.
I'm still confused though. I was aware of the fact that solve uses symvar to select the variables to solve for. Hence I used "a" as the variable name, because I figured it is selected first from symvar. Simply calling
answers = solve(equations);
In my above example doesn't work though.. How comes symvar picks the x's over the p? Or in other words: How robust is this solution?
A Jenkins
A Jenkins 2014년 1월 15일
Try this:
symvar(equations,length)
The documentation says it prefers variables "alphabetically closest to x."
Someone from TMW would have to comment on robustness, but I guess I agree that it seems natural to me that if you aren't sure, x,y,z are a good guess for variables and a,b,c are usually some kind of constant.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Numeric Solvers에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by