Last active
April 28, 2018 17:40
-
-
Save NassimBentarka/5d85c498ad46ff227000cb63a5907c70 to your computer and use it in GitHub Desktop.
Computes Fibonacci Numbers using Dynamic Programming Algorithm (Memoization) on MATLAB.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% This technique is mainly used to optimize the running time of the algorithm, it transfoms exponential time caused by the recursion | |
% into polynomial time. | |
% Run this file on Matlab (with the csv files in the same dir) | |
clear | |
clc | |
n=input("N= "); | |
memo=dlmread('data.csv'); %Read memoized values array | |
memo_index=dlmread('index.csv'); %Read indexes of the memoized values | |
fib(1)=1; | |
fib(2)=1; | |
if n<=2 | |
fib(n) | |
else | |
if ismember(n, memo_index) == 1 | |
memo(n) | |
disp('Computed using Dynamic Programming!'); | |
else | |
for i=3:1:n | |
fib(i)=fib(i-1)+fib(i-2); | |
memo(i)=fib(i); | |
memo_index(i)=i; | |
end | |
memo(n) | |
end | |
end | |
dlmwrite('data.csv',memo); %Update the file containing the array by adding the new computed values | |
dlmwrite('index.csv',memo_index); %Update the indexes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Before running, make sure to create two blank (csv) files with this names: "data.csv" and "index.csv" in the same directory as the code.