---
# System prepended metadata

title: 'Lesson 3: Loops'
tags: [Matlab Workshop]

---

---
tags: Matlab Workshop
---

# Lesson 3: Loops

:::info
There are two types of loops:
- `for` loop: for statements loop **a specific number of times**, and keep track of each iteration with an incrementing index variable.
- `while` loop: while statements **loop as long as a condition remains true.**
:::

## 1. `for` and `while` loop
A `for` loop is a programming construct that allows you to execute a block of code repeatedly, **with a fixed number of times**. It is used to iterate over a sequence of elements, such as an array, list or matrix.

```matlab
for i = 1:3
    disp(i);
end

% output:
1 
2
3
```

As for the `while` loop, once the **condition is true**, the looping block is executed repeatedly.

```matlab
i = 0; % initial value
while i < 3
    i = i + 1;
    disp(i);
end

% output:
1
2
3
```

:::warning
### Example 1
Using `for` loop to do summation. Calculate the result for 1 + 2 + 3 + ... + 10 = ?
```matlab
%Initialization
n = 10; 
sum = 0;

for i = 1:n % 
    sum = sum + i; 
    disp(sum)
end
```

Using `while` loop to do summation. Calculate the result for 1 + 2 + 3 + ... + 10 = ?
```matlab
n = 10; 
sum = 0;
i = 0;  % Initialize the counter

while i < n
    i = i + 1;
    sum = sum + i;
    disp(sum)
end
```
:::

:::warning
### Example 2
Here, we go back to our previous example in the if-else statement workshop. How can you apply `for` or `while` loop?
```matlab!
% Define nucleotide sequences as a list of character
seq1 = ['A', 'C', 'G', 'T', 'A', 'C'];  % ACGTAC
seq2 = ['A', 'C', 'G', 'A', 'A', 'T'];  % ACGAAT

% Check if the sequences are of the same length
if length(seq1) ~= length(seq2)
    disp('Error: Sequences must be of the same length.');
else
    % Use for/while loop to count the mismatch
    ...
end
```

[Here](https://hackmd.io/k4ni6ad7TRKt85VCPVQmeg?both)'s the place that you can put your code.
:::

:::success
### Take-home exercise
Calculate the geometric series 1 * 2 * 3 * ... * 5 using loops
:::

### Terminating condition ###
:::danger
To prevent an infinite loop using `while` loop, ensure the loop's condition becomes `false` at some point. If the condition remains true indefinitely, the program will get stuck in an endless loop.
```matlab
i = 0;

while i >= 0
    i = i + 1;
    fprintf("%d\n", i);
end
% program would not stop
```

If you inadvertently create an infinite loop (a loop that never ends on its own), stop execution of the loop by pressing **`Ctrl+C`**.
:::

## 2. Loop control

| Control Statement | Purpose                          |
|-------------------|----------------------------------|
| `break`           | Stops the loop manually when a condition is met. |
| `continue`        | Skips the current iteration when a condition is met. |

Using `break` ...
```matlab
i = 0;
while i < 3
    i = i + 1;
    if i == 2
        break;  % Exit the loop when i equals 2
    end
    disp(i);
end

% output:
1
```

Using `continue` ...
```matlab
i = 0;
while i < 3
    i = i + 1;
    if i == 2
        continue;  % Skip the current iteration when i equals 2
    end
    disp(i);
end

% output:
1
3
```

:::warning
### Example 3
After doing multiple sequence alignment using a pool of sequences (`seqA`, `seqB`, `seqC`, `seqD`, ...) having a length of 8 nucleotides, we want to find the sequences (i.e., `seqB`, `seqC`, `seqD`,...) that does not contain any **gap** and have more than 3 matches with `seqA` (we call this `valid_sequences`).

```matlab
% Define sequences
seqA = 'ACGTACGT';  % Reference sequence
sequences = {'AGGCACCT',   
             'ACCTCCGA',    
             'ACGTA--T',    
             'AAGTACGT',   
             'ACGTGCGT',   
             '--G-C---'};

% Initialize a cell array to store valid sequences
valid_sequences = {};

for i = 1:length(sequences)
    current_seq = sequences{i};
    
    % Check current_seq has `gap`
    if
        ...
    end
    
    % Count matches with seqA
    matches = 0
    for/while
        ...
        
        % Check the number of matches is larger than 3
        if matches > 3
            ...
        end
    end
end

% Display valid sequences
disp('Valid sequences without gaps and with more than 3 matches:');
disp(valid_sequences);
```
[Here](https://hackmd.io/k4ni6ad7TRKt85VCPVQmeg?edit)'s the place that you can put your code.

:::spoiler HELLO
```matlab=
% Define sequences
seqA = 'ACGTACGT';  % Reference sequence
sequences = {'AGGCACCT',   
             'ACCTCCGA',    
             'ACGTA--T',    
             'AAGTACGT',   
             'ACGTGCGT',   
             '--G-C---'};

% Initialize a cell array to store valid sequences
valid_sequences = {};

for i = 1:length(sequences)
    current_seq = sequences{i};
    
    % Check for gaps
    if contains(current_seq, '-')
        continue;  % Skip sequences with gaps
    end
    
    % Initialize match counter
    matches = 0;
    
    % Count matches with seqA
    for j = 1:length(seqA)
        if seqA(j) == current_seq(j)
            matches = matches + 1;  % Increment match counter
        end
        
        % Break if matches exceed 3
        if matches > 3
            valid_sequences{end+1} = current_seq;  % Store valid sequence
            break;  % Exit the inner loop
        end
    end
end
```

:::


:::success
### Take-home exercise
Assume x>0 and x is an integer, find the minimum x that statisfies ```x^2 - 27x + 170 = 0```
:::

## 3. Useful info: Nested Loops

Just like if-else statements, we can nest as many loops as we want.

```matlab
for i = 0:2
    for j = 0:1
        fprintf("%d %d\n", i, j);
    end
end

% output
0 0
0 1
1 0
1 1
2 0
2 1
```

:::info
### Exercise

#### Multiplication Table

Print Nine-Nine Multiplication Table (九九乘法表)

```matlab
for i = ...
    for j = ...
        fprintf(...)
    end
end


% You should print
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
...
9 x 9 = 81
```
:::

:::success

### Take-Home Exercise
#### Prime Number

Print all the prime numbers ranging from 2 to 100

```matlab
<solution>

for num = 2:100
    % we check whether "num" is a prime number
    
    % check prime by looping through all factors
    is_prime = true;
    for divisible_factor = 2:num-1
        if mod(num, divisible_factor) == 0 % whole division
           is_prime = false;
           break;
        end
    end

    % print the prime number
    if is_prime
        fprintf("%d\n", num);
    end
end
```
:::

