if x is a variable, solve for x

2 views (last 30 days)
I am open to any better ways of doing this. I am brand new to Matlab.
What I am trying to do is write a code to solve kinematic equations, and if the user inputs one of the prompts as a variable, then display the correlating variable. Example:
When promted
what is your x value? x %user inputs a variable as itself
what is your x_0 value? 0
what is your v_0 value? 5
what is your t value? 10
Final distance = 50
for any of the given options.
Hopefully this makes sense.
syms x x_0 v_0 t
equation = x==x_0+v_0*t
x= input('What is your x value?');
x_0 = input('What is your x_0 value?');
v_0 = input('What is your v_0 value?');
t = input('What is your t value?');
equation = x==x_0+v_0*t;
S=solve(equation,"IgnoreProperties",true);
if x==x
fprintf('Distance is %d\n', S)
else
;
end
if x_0==x_0
fprintf('Initial Distance is %d\n', S)
else
;
end
if v_0==v_0
fprintf('Initial Velocity is %d\n', S)
else
;
end
if t==t
fprintf('Time is %d\n', S)
else
;
end

Accepted Answer

Walter Roberson
Walter Roberson on 8 Apr 2021
If the user inputs a variable name for exactly one of the prompts, then symvar(equation) will tell you which variable it was.
solving_for = symvar(equation);
switch solving_for
case sym('x')
name = 'Distance';
case sym('x_0')
name = 'Initial Distance';
case sym('v_0')
name = 'Initial Velocity';
case sym('t')
name = 'Time';
otherwise
error('wrong variable to solve for');
end
fprintf('%s is %g\n', name, S);
  1 Comment
Kyle Langford
Kyle Langford on 8 Apr 2021
Awesome! Thank you! We have not covered any of that in my class yet.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!