Vectorization in MATLAB

⚡ Vectorization in MATLAB
It makes code faster, shorter, and more readable, which is why MATLAB strongly encourages it.
MATLAB is developed by MathWorks.
🔹 What Is Vectorization?
Vectorization is the technique of performing operations on entire arrays at once instead of element-by-element loops.
📌 MATLAB is optimized internally for vector & matrix operations.
🚀 Why Vectorization Is Important
🔥 Much faster execution
✨ Cleaner and shorter code
🧠 Closer to mathematical notation
💼 Interview & industry best practice
1️⃣ Loop vs Vectorized Code (Basic Example)
❌ Using Loop
Output
✅ Vectorized Version
✔ Same output, simpler & faster
2️⃣ Element-wise Operators (VERY IMPORTANT)
| Operator | Meaning |
|---|---|
.* | Element-wise multiplication |
./ | Element-wise division |
.^ | Element-wise power |
🔸 Example
Output
3️⃣ Vectorized Conditional Operations
❌ Using Loop
✅ Vectorized Using Logical Indexing
Output
4️⃣ Using Built-in Vectorized Functions
🔸 Example: sin, exp, sqrt
📌 Most MATLAB functions are vectorized by default.
5️⃣ Vectorization with sum, mean, max
Output
6️⃣ Replacing Nested Loops (Advanced Example)
❌ Nested Loops
✅ Vectorized Using meshgrid
Output
7️⃣ Vectorization with Tables
📌 No loops needed.
8️⃣ Performance Comparison (Conceptual)
📌 Vectorized code is significantly faster.
⚠️ Common Mistakes
Forgetting
.in.^,.*,./Mixing matrix and element-wise operations
Over-vectorizing at the cost of readability
🧠 When NOT to Vectorize
Complex logic with many branches
Very small loops (performance difference negligible)
When readability suffers badly
🎯 Interview Questions: Vectorization in MATLAB
🔹 Q1. What is vectorization?
Answer:
Replacing loops with vector/matrix operations.
🔹 Q2. Why is vectorization faster in MATLAB?
Answer:
Because MATLAB is optimized for array-based operations.
🔹 Q3. Difference between * and .*?
Answer:* → matrix multiplication.* → element-wise multiplication
🔹 Q4. How do you replace if inside loops?
Answer:
Using logical indexing.
🔹 Q5. Are all MATLAB functions vectorized?
Answer:
Most built-in functions are vectorized.
🔹 Q6. Is vectorized code always better?
Answer:
Not always—readability and logic also matter.
✅ Summary
Vectorization is a core MATLAB skill
Makes code faster and cleaner
Uses element-wise operators & logical indexing
Highly valued in interviews & real projects
