Q:

Fibonacci Sequence with Matlab using Loops(Iteration)

How do I write a Fibonacci function in Matlab using loops? Function must have two inputs.
inputs:
1.a number to start the sequence
2.the number of terms to return (must be a positive integer (N))
Output: is a 1xN vector of the Fibonacci sequence.
Conditions: If the initial term is 0 or 1, the second term will be 1. For any other number, the initial term will be repeated for the second number.
Thanks

A:

The definition of the Fibonacci sequence is the following:

The specifications for your function are rather odd, but nonetheless doable.  First you need to check if the initial term is 0 or 1.  If that's the case, the second term will be 1.  If anything else, the first two terms will be exactly the same as the initial term.  You'll require a bunch of if statements first.... so something like this:
function out = fibonacci(initial_term, N)

    if initial_term == 0 || initial_term == 1
        second_num = 1;
    else
        second_num = initial_term;
    end

    if N == 1
        out = initial_term;
    elseif N == 2
        out = [initial_term second_num];
    else
        out = zeros(1,N);
        out(1:2) = [initial_term second_num];
        for idx = 3 : N
            out(idx) = out(idx-1) + out(idx-2);
        end
    end
end

The first if statement checks to see if the initial term is either 0 or 1.  If it is, the second number will be 1.  If it isn't, the second number will be the same as the initial term.
Next, we check to see what N is.  If it's 1, then just return the initial term.  If it's 2, then return an array of the initial term and second term.  If it's anything larger, then create an output array of size N where the first two elements are initialized like in the case of N = 2, then we simply loop through and use the Fibonacci recurrence formula to populate each element in the output from index 3 and onwards.
You can also write the for loop as a while loop as well.  Remember, a while loop keeps iterating until the logical condition that the while loop checks becomes false.  As such, you would do:
out = zeros(1,N);
out(1:2) = [initial_term second_num];
idx = 3;
while idx <= N
    out(idx) = out(idx-1) + out(idx-2);
    idx = idx + 1;
end

Example Calls
>> out = fibonacci(3, 6)

out =

     3     3     6     9    15    24

>> out = fibonacci(0, 6)

out =

     0     1     1     2     3     5

>> out = fibonacci(4, 10)

out =

     4     4     8    12    20    32    52    84   136   220

