Logical Indexing
Instead of a loop, you can pull out exactly the elements of a vector that satisfy a condition, directly.
v = [3, -1, 4, -1, 5, -9, 2];
positives = v(v > 0);
disp(positives)
v > 0 produces a vector of 1s and 0s (true/false) the same size as v; indexing v with that keeps only the entries where it was true.
Replacing values that match a condition
v(v < 0) = 0;
disp(v)
Why This Matters for Your Exams
This is the single biggest "write it the MATLAB way, not the C way" habit -- the loop version works, but logical indexing is shorter, faster, and what an exam model-answer will almost always use.
Try it yourself
lock
Real-time practice is a paid add-on
Reading units and the practice quiz are free. Pay once to unlock running real code for LaTeX & MATLAB.

