Introduction to Programming with MATLAB Coursera All assignment Quiz Answer

Table of Content

Week-2

MATLAB as a Calculator

We borrowed $1000 at a 10% annual interest rate. If we did not make a payment for two years, and assumin Assign the result to a variable called debt.
money_borrowed=1000; 
interest_rate=.10;
end_loan_of_first_year=(money_borrowed*interest_rate)+money_borrowed
new_interest=end_loan_of_first_year*interest_rate 
debt=end_loan_of_first_year+new_interest 
 
Ans:-
 
money_borrowed=1000; 
interest_rate=.10;
end_loan_of_first_year=(money_borrowed*interest_rate)+money_borrowed
new_interest=end_loan_of_first_year*interest_rate 
debt=end_loan_of_first_year+new_interest 
 
Lesson 1 Wrap-up
 
1. As of early 2018, Usain Bolt holds the world record in the men's 100-meter dash. It is 9.58 seconds. called hundred.
 2.Kenyan Eliud Kipchoge set a new world record for men of 2:01:39 on September 16, 2018. Assign h distance is 42.195 kilometers.
 
Ans:-
 
distance_of_usain_bolt = 100 
distance_of_usain_bolt_in_km = distance_of_usain_bolt/1000 
time_of_usain_bolt= 9.58 
time_of_usain_bolt_in_hour= time_of_usain_bolt/3600
hundred=distance_of_usain_bolt_in_km/time_of_usain_bolt_in_hour 
distance_of_eliud= 42.195 
time_of_eliud_in_minute=2*60+1+(39/60) 
time_of_eliud_in_hour=time_of_eliud_in_minute/60 
marathon=distance_of_eliud/time_of_eliud_in_hour
 

Week-3

Colon Operator Practice

1. Create a vector of all the odd positive integers smaller than 100 in increasing order and save it into variable odds. 
2. Create a vector of all the even positive integers smaller than or equal to 100 in decreasing order and save it into variable evens. 
 
Ans:-
 
odds=[1:2:100] 
evens=[100:-2:2]
 
 
 

Matrix Indexing Practice

Given matrix A, assign the second column of A to a variable v. Afterwards change each element of the last row of A to 0
 
Ans:-
 
A = [1:5; 6:10; 11:15; 16:20]; 
A=[1:5; 6:10; 11:15; 16:20]; 
v=A(1:4,2)
A(4,1:5)=0
 
 

Matrix Arithmetic

 
Given a Matrix A, 
  • Create a row vector of 1's that has same number of elements as A has rows. 
  • Create a column vector of 1's that has the same number of elements as A has columns. 
  • Using matrix multiplication, assign the product of the row vector, the matrix A, and the column vector (in this order) to the variable result. 
Think about what the result represents...
 
Ans:-
 
A = [1:5; 6:10; 11:15; 16:20]; 
B=[1 1 1 1] 
C=[1;1;1;1;1] 
result=B*A*C  

 

Week-4 

A Simple Function 

Write a function called tri_area that returns the area of a triangle with base b and height h, where b and h are input arguments of the function in that order.

 
Ans:-

function area=tri_area(b,h) 
area=0.5*b*h; 
end 

Corner Case

Write a function called corners that takes a matrix as an input argument and returns four outputs: the elements at its four corners in this order: top_left, top_righ and bottom_right. (Note that loops and if-statements are neither necessary nor allowed as we have not covered them yet.) See an example run below: 
>> [a, b, c, d] = corners([1 2; 3 4]) 
a = 1 
b = 2 
c = 3 
d = 4 
 
Ans:-
 
function [a,b,c,d]=corners(A) 
[m,n]=size(A); 
a=A(1,1); 
b=A(1,n); 
c=A(m,1); 
d=A(m,n); 
end
 

Taxi Fare 

Write a function called taxi_fare that computes the fare of a taxi ride. It takes two inputs: the distance in kilometers (d) and the amount of wait time in minutes (t). 
calculated like this: 
  • the first km is $5 
  • every additional km is $2 
  • and every minute of waiting is $0.25. 
Once a km is started, it counts as a whole (Hint: consider the ceil built-in function). The same rule applies to wait times. You can assume that d >0 and t >= 0 but necessarily integers. The function returns the fare in dollars. For example, a 3.5-km ride with 2.25 minutes of wait costs $11.75. Note that loops and if-statements necessary nor allowed.
 
Ans:-
 
function fare=taxi_fare(d,t) 
d=ceil(d); 
t=ceil(t); 
k=ceil(d-1); 
fare=5+2*k+0.25*t; 
end
 

Week-5

Assignment: Built-in functions

Minimum and Maximum 

Write a function called minimax that takes M, a matrix input argument and returns mmr, a row vector containing the absolute values of the difference between the minimum valued elements in each row. As a second output argument called mmm, it provides the difference between the maximum and minimum element in the the code below for an example: 

>> A = randi(100,3,4) 
A = 66 94 75 18 4 68 40 71 85 76 66 4 
>> [x, y] = minimax(A) 
x = 76 67 81 
y = 90
 
Ans:-
 
function [mmr,mmm]=minimax(A) 
mmt = [max(A,[],2)-min(A,[],2)]; 
mmr=mmt' 
mmm=max(A,[],"all")-min(A,[],"all") 
 

Assignment: Lesson 4 Wrap-up

 Matrix Construction

Write a function called trio that takes two positive integer inputs n and m. The function returns a 3n-by-m matrix called T. The top third of T (an n by m submatrix) middle third is all 2-s while the bottom third is all 3-s. For an example,see the code below: 
M = trio(2,4) 
M = 1 1 1 1 1 1 1 1 
       2 2 2 2 2 2 2 2 
       3 3 3 3 3 3 3 3 
 
Ans:-
 
function T=trio(n,m); 
n=3*n; 
T1=ones(n/3,m); 
T2=2*ones(n/3,m); 
T3=3*ones(n/3,m); 
T=[T1;T2;T3]; 
 

Week-6

Assignment: If-statement practice

Practice if-statements

Write a function called picker that takes three input arguments called condition, in1 and in2 in this order. The argument condition is a logical. If it is true, the fun
value of in1 to the output argument out, otherwise, it assigns the value of in2 to out. See the examples below to see how picker works in practice.
a = 2;
b = 3;
picker(a<b,a,b)
ans =
 2
picker(a<0,1,-1)
ans =
 -1
Ans:-
 
function out=picker(condition,in1,in2) 
y=logical(condition) 
if y ==1 
   out=in1; 
else 
   out=in2; 
end 
end 
 

Assignment: More practice

More Practice 

Write a function called eligible that helps the admission officer of the Graduate School of Vanderbilt University decide whether the applicant is eligible for admissi scores. The function takes two positive scalars called v and q as input and returns the logical admit as output. They represent the percentiles of the verbal and qu portions of the GRE respectively. You do not need to check the inputs. The applicant is eligible if the average percentile is at least 92% and both of the individual p over 88%. The function returns logical true or false value. 
 
Ans:-
 
function admit=eligible(v,q); 
if((v+q)/2>=92 && v>88 && q>88) 
    admit=true 
else 
    admit=false 
end
end
 

Assignment: nargin

Variable Number of Input Arguments

Write a function called under_age that takes two positive integer scalar arguments: 
  • 1. age that represents someone's age, and 
  • 2. limit that represents an age limit. 
The function returns true if the person is younger than the age limit. If the second argument, limit, is not provided, it defaults to 21. You do not need to check that positive integer scalars. The name of the output argument is too_young. 
 
Ans:-
 
function too_young=under_age(age,limit)
if nargin<2
limit=21;
end
if age<limit
 too_young=true;
else
 too_young=false;
 return
end
end
 

Assignment: Lesson 5 Wrap-up

Lesson 5 Wrap-up 

Write a function called valid_date that takes three positive integer scalar inputs year, month, day. If these three represent a valid date, return a logical true, othe name of the output argument is valid. If any of the inputs is not a positive integer scalar, return false as well. Note that every year that is exactly divisible by 4 is a except for years that are exactly divisible by 100. However, years that are exactly divisible by 400 are also leap years. For example, the year 1900 was not leap ye 2000 was. Note that your solution must not contain any of the date related built-in MATLAB functions. 
 
Ans:-
 
function valid = valid_date(year,month,day)
if sum(rem([year,month,day],1))==0 && sum([year,month,day]>0)==3
if ismember(month,[1,3,5,7,8,10,12]) && day<32
valid=true;
elseif ismember(month,[4,6,9,11]) && day<31
valid=true;
elseif month==2 && ismember(sum(rem(year,[4,100,400])==0),[1,3]) && day<30
valid=true;
elseif month==2 && ismember(sum(rem(year,[4,100,400])==0),[0,2]) && day<29
valid=true;
else
valid=false;
end
else
valid=false;
end
 

Week-7

Assignment: for-loop practice

Practice for-loops 

Write a function called halfsum that takes as input a matrix and computes the sum of its elements that are in the diagonal and are to the right of it. The diagonal i set of those elements whose column and row indexes are the same. In other words, the function adds up the element in the uppertriangular part of the matrix. The output argument is summa. For example, with the matrix below as input 
A = 
     1 2 3 
     4 5 6 
     7 8 9 
The function would return 26 (1 + 2 + 3 + 5 + 6 + 9 = 26)
 
Ans:-
 
function summa = halfsum(M)
[a b] = size(M);
if a>1
 
for n = 1:a;
 for m = 1:b;
 if n>m;
 M(n,m) = 0;
 summa = sum(sum(M));
 end
 end
end
else
 summa = sum(M);
end
 
end
 

Assignment: while-loop practice

Practice while-loops

Write a function called next_prime that takes a scalar positive integer input n. Use a while-loop to find and r use the built-in isprime function. 
Here are some example runs: 
>> next_prime(2) ans = 3 
>> next_prime(8) ans = 11 
>> next_prime(12345678) 
      ans = 12345701 
 
Ans:- 
 
function k = next_prime(n) 
k = n + 1 
% now k = input + 1 
while isprime(k) == 0 
% if the k is not prime add 1 till its prime 
       k = k+1; 
      % when its prime thats the answer end the loop
end 
end

Assignment: Logical Indexing

Logical Arrays Practice

Write a function called freezing that takes a vector of numbers that correspond to daily low temperatures in temperatures (that is, lower than 32 F) without using loops. 
Here is an example run: 
numfreeze = freezing([45 21 32 31 51 12]) 
numfreeze = 3
 
Ans:-
function numfreeze=freezing(T) 
T(T<32)=1; 
T(T>=32)=0; 
numfreeze=sum(T); 
 


Assignment: Lesson 6 Wrap-up

Lesson 6 Wrap-up

Write a function called max_sum that takes v, a row vector of numbers, and n, a positive integer as inputs. T is the largest possible. In other words, if v is [1 2 3 4 5 4 3 2 1] and n is 3, it will find 4 5 and 4 because their such sequences exist in v, max_sum returns the first one. The function returns summa, the sum as the first consecutive ones as the second output. If the input n is larger than the number of elements of v, the function runs: 
[summa, index] = max_sum([1 2 3 4 5 4 3 2 1],3) 
        summa = 13 
        index = 4 
[summa, index] = max_sum([1 2 3 4 5 4 3 2 1],2) 
        summa = 9 
        index = 4 
[summa, index] = max_sum([1 2 3 4 5 4 3 2 1],1) 
        summa = 5 
        index = 5 
[summa, index] = max_sum([1 2 3 4 5 4 3 2 1],9) 
        summa = 25 
        index = 1 
[summa, index] = max_sum([1 2 3 4 5 4 3 2 1],10) 
        summa = 0 
        index = -1  
 
Ans:-
 
function [summa, index] = max_sum(v,n) 
L = length(v); 
S=zeros(1,L-n+1); 
if n > L 
      summa = 0; 
      index = -1; 
      return 
else 
      for i = 1:(L-n+1) 
      S(i)=sum(v(i:(i+n-1))); 
      end 
summa = max(S); 
ind = find(S == summa); 
index = min(ind); 
end 
end 
 

Week-8

 

Assignment: Character Vectors

Simple Encryption


 
Ans:-
 
function txt = caesar(txt,key) 
    txt = double(txt) + key; 
    first = double(' '); 
    last = double('~'); 
    % use mod to shift the characters - notice the + 1 
    % this is a common error and results in shifts 
    % being off by 1 
    txt = char(mod(txt - first,last - first + 1) + first); 
end
 
 

Assignment: Using Cell Arrays

Sparse Matrix


 
Ans:-
 
function matrix=sparse2matrix(cellvec) 
matrix=cellvec{1,2}*ones(cellvec{1,1}); 
[m n]=size(cellvec); 
for i=3:n 
    A=cellvec{1,i}; 
    p=A(1); 
    q=A(2); 
    matrix(p,q)=A(3); 
end 
end
 
 

Week-9

Assignment: Excel Files

Excel File I/O


 
Ans:-
 function distance = get_distance(city1, city2) 
[~,~,raw] = xlsread('Distances.xlsx'); 
index_list_1 = strcmp(city1,raw(:,1)); 
index_list_2 = strcmp(city2,raw(1,:)); 
if all(index_list_1 == 0) || all(index_list_2 == 0) 
   distance = -1; else 
   distance = raw{(index_list_1 == 1), (index_list_2 == 1)}; 
end
 

Assignment: Text Files

Text File I/O


Ans:-
 
function charnum = char_counter(fname,character) 
 fid = fopen(fname,'rt'); 
 if (fid<0) || ~ischar(character) 
 charnum = -1; 
 else
 oneline = fgets(fid);
 charnum = 0; 
 while (ischar(oneline)) || (strcmp(character,oneline)==1) 
 f = strfind(oneline,character); 
 charnum = charnum + length(f);
 oneline = fgets(fid); 
   end 
 end 
end 

Final Problems Week-9

Assignment: Saddle Points

Saddle Points

Write a function called saddle that finds saddle points in the input matrix M. For the purposes of this problem or equal to every element in its row, and less than or equal to every element in its column. Note that there m that has exactly two columns. Each row of indices corresponds to one saddle point with the first element of t element containing the column index. If there is no saddle point in M, then indices is the empty array.
 
Ans:-
 
function indices=saddle(M) 
indices=[]; 
[a b]=size(M); 
q=1; 
for i=1:a 
 for j=1:b 
 x=M(i,:); 
 y=M(:,j); 
 c=M(i,j)>=x; 
 d=M(i,j)<=y; 
 if ~ismember(0,c) && ~ismember(0,d) 
 indices(q,1)=i; 
 indices(q,2)=j; 
 q=q+1; 
 end 
 end 
end 
end  
 

Assignment: Image Blur

Image blur

Ans:-
 
function output = blur(img,w) 
B=double(img); 
[m,n] = size(B); 
k=2*w+1; 
for i = 1:m 
 for j = 1:n 
 p=i-fix(k/2); 
 q=i+fix(k/2); 
 r=j-fix(k/2); 
 s=j+fix(k/2);
 if p<1 
 p=1; 
 end 
 if q>m 
 q=m; 
 end 
 if r<1 
    r=1; 
 end 
 if s>n 
 s=n; 
 end 
 A=B([p:q],[r:s]); 
 C(i,j)=mean(A(:)); 
 end 
end 
output=uint8(C); 
end  
 
 

Assignment: Echo Generator

Echo Generator

 
Ans:-
 
function output = echo_gen(in,fs,delay,gain) 
samples = round(fs*delay) ; 
ds = floor(samples); 
signal = zeros(length(in)+ds,1); 
signal(1:length(in))=in; 
echo_signal =zeros(length(in)+ds,1); 
echo_signal(ds+(1:length(in*gain)))=in*gain; 
output= signal + echo_signal; 
p= max(abs(output)); 
if p>1 
output=output ./ p; 
else 
output = output; 
end 
end 
 
 
That's The All Ans of Quiz and Assignment of Introduction to Programming with MATLAB Coursera.

6 comments

Ask Doubt or Any Question You Have - Let's Disguss !!

  1. Thank you
  2. Very helpful code
  3. BAHUT
  4. thanks bro
  5. Thanks sir
  6. thanks sir
share