Problem
Write a program in Matlab to ask the user with the length of the two sides and angle between two sides. Then use the following relation to calculate the third side of the triangle:
Equation to calculate the third side of the triangle if two sides and angle is given |
Solution
We can solve this right hand side of the equation to get the value of the third side. But we will have to write the above equation to matlab equivalent. It is very easy and we will solve using functions.
I suggest you refer to program section and then refer to the explanation section to get a detailed explanation of the same.
Some of the concepts you need to know to solve the problem are as follows:
1) Matlab functions
2) Operator Precedence
3) input function
4) Matlab Variables
5) fprintf in Matlab
1) Matlab functions
2) Operator Precedence
3) input function
4) Matlab Variables
5) fprintf in Matlab
Program 1
This is functional approach
1 2 3 4 5 | function size = third_side_function(a,b,theta) %third_side(a,b,theta) will give the length of third side of triangle size = a^2 + b^2 - a*b*cos(theta); end |
Line 1: Function initiation using the Matlab functions.
Line 2: This is matlab comment and also function documentation.
Line 4: Matlab equivalent of the given equation
Program 2
1 2 3 4 5 6 7 8 9 | %This script will calculate the third side length in a triangle a = input('Enter the length of first side: '); b = input('Enter the length of second side: '); theta = input('Enter the angle between the above in radians: '); c = a^2+b^2-a*b*cos(theta); fprintf('Length of third side is: %.4f',c); |
Explanation 2
First line is matlab comments.
3-5 lines are taking the user input for calculations.
Line7: I have written matlab equivalent of the equation given in the question.
Line9: I am printing the length of the third side so that the user get to know the same in a clean and neat format!
Input/output
Third side of a triangle calculation using Matlab |
Final note
I have tried to explain every part in the post in such a way that it is easy for everyone to understand. If you have not understood anything or have any doubt then please do contact me or comment in the comment box below. You can contact me from here: contact me.
The above program was high lighted using hilite.me .
Keywords: third side,