4
4
Write a matlab function myT that takes as input a matrix A and outputs a matrix B. The
entry in row j and column i of B should be the element from row i and column j of A. You
should do this using for loops.
%%
function B = myT(A)
[m,n] = size(A);
B = zeros(m,n);
for i=1:m
for j=1:n
B(j,i) = A(i,j);
end
end
end
problem 2
Write a matlab function mysumvect that takes as input a vector v and an integer n. Write a
while loop that adds up the elements of v until the sum (denoted as x) is greater than n. If
the end of the vector is met and n has not been reached, then let x equal the sum of the
whole vector v. Output the variable x and a variable, iter, that counts the number of
iterations of the loop done to complete the task. Test the function with v =[10. -2, 8, 6. -4.
5,16, 20, 3]. Run with n=30, n=60, and n=20.
%%
function [x, iter] = mysumvect(v, n)
x = 0;
iter = 0;
while x <= n
x = x + v(iter + 1);
iter = iter + 1;
if iter == length(v)
break
end
end
end
Test 1:
[x, iter] = mysumvect([10, -2, 8, 6, -4, 5, 16, 20, 3], 30)
x=
43
iter =
6
Test 2:
[x, iter] = mysumvect([10, -2, 8, 6, -4, 5, 16, 20, 3], 60)
x=
93
iter =
8
Test 3:
[x, iter] = mysumvect([10, -2, 8, 6, -4, 5, 16, 20, 3], 20)
x=
29
iter =
4
Problem 3
Matlab code that generates n terms of Fibonacci sequence. Have input n and output the
value f consisting of the first n numbers of the sequence
%%
n = input('Enter n: ');
f = zeros(1, n);
if n >= 1
f(1) = 1;
end
if n >= 2
f(2) = 1;
end
for i = 3:n
f(i) = f(i-1) + f(i-2);
end
disp(f);
problem 4
Write a MATLAB function myEvenFibonacci by modifying the myFibonacci function to
find all of the even Fibonacci numbers in the first n
terms of the sequence. Store the even values in a vector called F_even, and output this from
the function. If there are no even numbers.
output an empty vector F_even = []. Test your function with n=23.
(Hint: You will need to use the MATLAB function mod(x,d) , which computes the
remainder of x after division by d . For example.
mod(23,4) returns 3 because 20 divided by 4 is 5 remainder 3. Think of how you can use
mod() to determine if a number is even, or in
other words, divisible by 2.)
function F_even = myEvenFibonacci(n)
% Use the myFibonacci function to generate the first n terms of the sequence
F = myFibonacci(n);
% Loop through F
for i=1:length(F)
end
end
end