MATLAB: How to use syms & solve in a function

functionMATLABsolve

Hi,
I have a 3 equation 3 variable system which I can solve in cmd window using this code:
v1=10;
v2=5;
v3=4*I1;
r1=6;
r2=20;
r3=15;
r4=6;
r5=10;
rl=8;
eqn = [0==v1-(r1*I1)-(r2*I2),0==(r2*I2)-(r3*(I1-I2))+v2-(r4*I3)-(v3),0==(v3)+(r4*I3)-((r5+rl)*(I1-I2-I3))];
sol = solve(eqn);
sol.I1,sol.I2,sol.I3
This works fine and gives me the correct values for I1,I2,I3. I have more to do with set of equations. Specifically I need to solve for multiple values for RL so would like to make the above code a function that I can call from the cmd window.
I am struggling to work out how to structure the function. Could you please give me some hints on what would me the most efficient/eloquent?

Best Answer

syms I1 I2 I3 rl
v1=10;
v2=5;
v3=4*I1;
r1=6;
r2=20;
r3=15;
r4=6;
r5=10;
eqn = [0==v1-(r1*I1)-(r2*I2),0==(r2*I2)-(r3*(I1-I2))+v2-(r4*I3)-(v3),0==(v3)+(r4*I3)-((r5+rl)*(I1-I2-I3))];
[I1, I2, I3] = solve(eqn, [I1, I2, I3]);
fun = matlabFunction([I1, I2, I3]);
You can now call fun() with a scalar or column vector argument of rl values. The corresponding I1, I2, I3 values will be returned across the columns.