Basic math (addition, subtraction, multiplication, etc.) syntax in MATLAB is the same as it is in most calculators (+, -, *, /, ^). These syntax are the same whether used with variables or numbers directly. See MathWorks for a full list of MATLAB operators.
Important Note: You must use the multiplication operator everywhere you have multiplication. 7x should be 7*x. 7(x+1) should be 7*(x+1). You will get an error if you are missing a multiplication operator.
result = 3*(4 + 1) %Example with just numbers %Defining some arbitrary variables a = 3; b = 10; c = 1; product = a*b*c %Multiplying variables difference = a - c %Subtracting variables exponent = b^a %Raising a variable to an exponentCommand Window Output
result = 15 product = 30 difference = 2 exponent = 1000 [Try this code yourself with Octave Online! Click Here]
Finding the values of trigonometric functions is done in MATLAB by using the conventional abbreviated version of the function; i.e., sin(), cos(), or tan(). MATLAB assumes argument of a trig function is in radians. For an input in degrees, add the letter “d” to the end of the trigonometric function (e.g., sind()).
Important Note: By default MATLAB assumes argument is in radians.
angle = 180; %Defining angle as a variable to allow for easy changes radSin = sind(angle); %Finding sine of 'angle' in degrees fprintf('The value of sin(%g) is %g\n.',angle,radSin) %Note: The variable "pi" is defined in MATLAB by default radTan = tan(pi/3) %Finding tangent of pi/3 invCos = acos(1) %Finding inverse cosine of 1Command Window Output
The value of sin(180) is 1.22465e-16. radTan = 1.7321 invCos = 0 [Try this code yourself with Octave Online! Click Here]
The two most common logarithmic bases, 10 and e, have explicit functions in MATLAB. The natural log (log base e) in MATLAB can be found using the function log(). Log base 10 (log10) is the function log10(). The logarithm of any real and positive base can be found with the change of base formula.
Important Note: “ln” is NOT the function for natural log in MATLAB. log(), as noted previously, is the function for natural log.
ln = log(30); %finding natural log of 30 fprintf('The natural log of 30 is %g\n.',ln) base10 = log10(7) %finding log base 10 of 7Command Window Output
The natural log of 30 is 3.4012. base10 = 0.8451 [Try this code yourself with Octave Online! Click Here]
e4 = exp(5) %Finding e^5 x = 1; %Define an arbitrary variable x ex = exp(x) %Finding e^xCommand Window Output
e4 = 148.4132 ex = 2.7183 [Try this code yourself with Octave Online! Click Here]
In the next lesson, we will explore implementing unknown variables into MATLAB and how to use them to solve for the roots of an equation.