Professional Documents
Culture Documents
BS ChE—1B
Final Machine Problem
Computer Fundamentals and Programming
1. FIBONACCI SEQUENCE FUNCTION
Create a function to generate a Fibonacci sequence. A
Fibonacci sequence is a vector of numbers where each number
(except the 1st and 2nd numbers) is the sum of the immediate
previous numbers.
First Run:
CODES IN EDITOR:
function [s] = Fibonacci (x, y, n)
x= 'input first term of the Fibonacci sequence: ';
input_first_term = input(x);
y = 'input second term of the Fibonacci sequence: ';
input_second_term = input (y);
n = 'input number of elements: ';
input_element_number = input (n);
s(1) = input_first_term;
s(2) = input_second_term;
n = input_element_number;
for n = 3:input_element_number
s(n) = s(n-2) + s(n-1);
endfor
endfunction
Second Run:
CODES IN COMMAND WINDOW:
>> fibonacci(1, 0, 12)
input first term of the Fibonacci sequence: 1
input second term of the Fibonacci sequence: 0
input number of elements: 12
DOCUMENTATION:
2. MAGIC SQUARE
Create a script file named magicsquare. The script will
first ask from the user for a perfect square number and store it
in a variable n_squared. Then it should generate a vector which
is a jumbled combination of numbers 1 to n_squared. The vector is
placed or distributed in an nxn matrix in the manner shown in the
examples.
Hint: Use for 2 for loops, where one for loop is nested or inside
the other for loop.
CODES IN EDITOR:
function [s] = magicsquare
magicsquare = 'Enter a perfect square number:';
n_squared = input(magicsquare)
x = randperm(n_squared)
A = reshape([x], sqrt(n_squared), sqrt(n_squared))
Endfunction
CODES IN COMMAND WINDOW:
>> magicsquare
2 3 4 1
A =
2 4
3 1
>> magicsquare
Enter a perfect square number:4
n_squared = 4
x =
4 2 3 1
A =
4 3
2 1
>> magicsquare
Enter a perfect square number:9
n_squared = 9
x =
7 5 2 1 9 6 3 8 4
A =
7 1 3
5 9 8
DOCUMENTATION: