Specify Order of Solutions using MATLAB solve?

Hello,
I'm trying to solve a system of equations using the MATLAB solve function with the following code:
XCell = num2cell(X);
Solutions = solve(Equations==0, XCell{:});
The vector X contains the variables for which I want to solve for and Equations is a matrix of equations. I want the order of Solutions to match the order of X. However it is returning the solutions in alphabetical order. (In order words the first element of struct2cell(Solutions) is the solution for the earliest variable in the alphabet, not the first element in X.) How can I fix this?
Thank you,
Kevin

 Réponse acceptée

The documentation for solve does say,
Solve this system of equations and assign the solutions to variables b and a. To ensure the correct order of the returned solutions, specify the variables explicitly. The order in which you specify the variables defines the order in which the solver returns the solutions.
Keep in mind, though, that the "order" for that purpose is relevant to using the
[var1, var2, ....] = solve()
form of solve. When you assign to a single variable on the left hand side, the output will be a structure, and struct2cell() is going to give you whatever order the fieldnames happened to be in for the struct. If that is important to you then,
numvar = length(X);
sols_cell = cell(numvar, 1);
for K = 1 : numvar
sols_cell{K} = Solutions.(X{K});
end

7 commentaires

On the line sols_cell{K} = Solutions.(X{K}) I'm getting an error: "Error using sym/subsref Too many output arguments."
To check, what does size(Solutions) and class(Solutions) indicate? Also please show numvar and class(X) and size(X) and X{1}
Kevin Bachovchin
Kevin Bachovchin le 7 Déc 2013
Modifié(e) : Kevin Bachovchin le 7 Déc 2013
size(Solutions)
ans =
1 1
class(Solutions)
ans =
struct
numvar
numvar =
2
class(X)
ans =
sym
size(X)
ans =
2 1
X(1)
ans =
dqC_dt
Ah, okay, try
sols_cell{K} = Solutions.(char(X(K)))
Thanks, that works perfectly!
Is there any option to force the output of "solve" to be a struct (with one field) instead of a "sym" when X contains only one element?
Good question. Unfortunately I do not have the toolbox to test with.

Connectez-vous pour commenter.

Plus de réponses (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by