0
0
MATLABdata~5 mins

Arithmetic operators in MATLAB

Choose your learning style9 modes available
Introduction

Arithmetic operators help you do math with numbers in your program. They let you add, subtract, multiply, and divide easily.

Calculating the total cost of items in a shopping cart.
Finding the average score of a test.
Converting temperatures between Celsius and Fahrenheit.
Calculating the area or perimeter of shapes.
Updating a counter or timer in a program.
Syntax
MATLAB
result = a + b;  % addition
result = a - b;  % subtraction
result = a * b;  % multiplication
result = a / b;  % division
result = a ^ b;  % power (exponentiation)
Use + for adding numbers, - for subtracting, * for multiplying, / for dividing, and ^ for powers.
Make sure variables a and b have numbers before using these operators.
Examples
Adds 5 and 3, stores 8 in x.
MATLAB
x = 5 + 3;
Subtracts 4 from 10, stores 6 in y.
MATLAB
y = 10 - 4;
Multiplies 7 by 2, stores 14 in z.
MATLAB
z = 7 * 2;
Divides 20 by 5, stores 4 in w.
MATLAB
w = 20 / 5;
Raises 3 to the power of 2, stores 9 in p.
MATLAB
p = 3 ^ 2;
Sample Program

This program shows how to use arithmetic operators with two numbers, 8 and 4. It prints the results of adding, subtracting, multiplying, dividing, and raising to a power.

MATLAB
% Simple arithmetic operations in MATLAB

a = 8;
b = 4;

sum_result = a + b;
diff_result = a - b;
prod_result = a * b;
quot_result = a / b;
power_result = a ^ b;

fprintf('Sum: %d\n', sum_result);
fprintf('Difference: %d\n', diff_result);
fprintf('Product: %d\n', prod_result);
fprintf('Quotient: %d\n', quot_result);
fprintf('Power: %d\n', power_result);
OutputSuccess
Important Notes

Division by zero will cause an error or return Inf in MATLAB.

Use parentheses to control the order of operations if needed.

Power operator (^) works with integers and decimals.

Summary

Arithmetic operators let you do basic math in MATLAB.

Use +, -, *, /, and ^ for addition, subtraction, multiplication, division, and powers.

Always check your numbers and use parentheses to avoid mistakes.