0
votes

I am writing Matlab code to solve equations with an unknown number of sym variables. The number of variables supplied by the user. Here is code for three sym variables, but the code produces an error.

clc;
clear
format long;
m=3;
mv = sym(zeros(m, 1));
for k=1:m
    mv(k,1) = sym(sprintf('m%d', k));
end
display(mv)
A=[  1.000   2.000   3.000     
 2.000  -2.000  -3.000     
  3.000   -3.000   7.000    
];
B=[1;0;5];
w=A*mv-B
s=solve(w==0)
F=s.mv;
display(F)

This is not different from solving a simple equation with solve.

1
Please share the error message you receive and on what line you get it.Adriaan
Reference to non-existent field 'mv'. Error in test (line 17) F=[s.mv]masih
You probably have a bunch of variables: s.m1, s.m2, etc.Andras Deak
yes but i don know how to get like this:masih
You probably want for k=1:m, mv(k,1)=s.(sprintf('m%d',k)); end after the solve, then use F=mv; as you intended to. OR: F=struct2cell(s); F=[F{:}].';.Andras Deak

1 Answers

2
votes

You shouldn't be using solve for a linear problem like this. sym/linsolve would be a much better choice, doesn't require creating additional variables, and returns the solution as a vector:

A = sym([1.000   2.000   3.000     
         2.000  -2.000  -3.000     
         3.000  -3.000   7.000    
        ]);
B = sym([1;0;5]);
s = linsolve(A,B)

returns

s =

    1/3
 -22/69
  10/23

Note that if you don't explicitly convert A and/or B to a symbolic array the numeric version of linsolve will be used and the solution will be returned in floating point.

If you really want to use solve, your for loop is unnecessary as simple call to sym can be used:

m = 3;
mv = sym('m',[m 1])
A = sym([1.000   2.000   3.000     
         2.000  -2.000  -3.000     
         3.000  -3.000   7.000    
        ]);
B = sym([1;0;5]);
w = A*mv-B;
s = struct2cell(solve(w==0))
s = [s{:}].'

In both case you can use vpa and/or double to convert the solutions to a numeric format.