write a fibonacci search method code in matlab

Here's an implementation of the Fibonacci search method in MATLAB:

main.m
function index = fibonacciSearch(arr, value)
    n = length(arr);
    
    % Initialize Fibonacci numbers
    fib1 = 0;
    fib2 = 1;
    fib3 = fib1 + fib2;
    
    while (fib3 < n)
        fib1 = fib2;
        fib2 = fib3;
        fib3 = fib1 + fib2;
    end
    
    offset = -1;
    
    while (fib3 > 1)
        % Check if fib1 is a valid index
        i = min(offset + fib1, n);
        
        % If value is greater than the current element in array, move the
        % Fibonacci sequence two steps down
        if (arr(i) < value)
            fib3 = fib2;
            fib2 = fib1;
            fib1 = fib3 - fib2;
            offset = i;
        % If value is lesser than the current element in array, move the
        % Fibonacci sequence one step down
        elseif (arr(i) > value)
            fib3 = fib1;
            fib2 = fib2 - fib1;
            fib1 = fib3 - fib2;
        else
            % Element found, return its index
            index = i;
            return;
        end
    end
    
    % Compare the last element with value
    if (fib2 == 1 && arr(n) == value)
        index = n;
    else
        % Element not found
        index = -1;
    end
end
1179 chars
49 lines

You can use the fibonacciSearch function to search for a specific value in an array. The function returns the index of the value if found, or -1 if not found.

related categories

gistlibby LogSnag