1.
Variables Declaration and Example
In MATLAB, a variable is like a storage container for data. You dont need to define the typeMATLAB
figures it out!
How to Declare a Variable:
x = 10; % A number
name = 'Ali'; % A text
status = true; % A logical value
Rules:
- Must begin with a letter
- Can include letters, numbers, underscores
- Case-sensitive (e.g., score = Score)
Tip: Use meaningful names like `averageScore` instead of just `a` or `x`.
2. Vectors and Matrices
Vectors and Matrices are basic data structures in MATLAB.
Vectors:
- Row vector: a = [1 2 3]
- Column vector: b = [1; 2; 3]
Matrix:
- A = [1 2 3; 4 5 6]
Differences:
- Vectors = one dimension (1D)
- Matrices = two dimensions (2D)
- Matrices support advanced operations like multiplication, transpose, and inverse
Use Case:
- Vectors: storing scores, temperatures
- Matrices: image data, linear equations
3. Loop Instruction
Loops help you repeat actions!
1. For Loop:
Used when you know how many times to repeat.
Example:
for i = 1:5
disp(i)
end
2. While Loop:
Used when you repeat *until* something happens.
Example:
i = 1;
while i <= 5
disp(i)
i = i + 1;
end
Tip: Make sure your while loop ends; otherwise, it runs forever!
4. Condition in MATLAB
Conditions help MATLAB make decisions using if-else logic.
Example:
x = 5;
if x > 0
disp('Positive')
elseif x == 0
disp('Zero')
else
disp('Negative')
end
Types:
- if
- if-else
- if-elseif-else
- Nested conditions
You can also use logical operators:
- && (and)
- || (or)
- ~ (not)
Conditionals = essential for building smart, responsive programs!