Solutions to Selected Exercises

I've had many request for solutions so here are some for the simpler exercises. Caveat: I hope the following solutions work but my typing and brain are sometimes not in sync. If you find errors, please let me know.

If your solution looks different - great! Differences are good. Do you know why? Finding out might be worthwhile and you are welcome to send a note to let me know what you've found.


[Back to main page] [Back to exercises page]

Basic exercises

   1. x = 32:2:75
    
   2. x = [2 5 1 6]
      a = x + 16
      b = x(1:2:end) + 3
      c = sqrt(x) or c = x.^(0.5)
      d = x.^2 or d = x.*x
    
   3. x = [3 2 6 8]', y = [4 1 3 5]'
      a = y + sum(x)
      b = x.^y
      c = x./y
      z = x.*y
      w = sum(z)
      x'*y - w   (same thing)
    
   5. The function "rats" just displays the contents of a variable
      a = 2:2:20  (or whatever max #)
      b = 10:-2:-4
      c1 = 1:5, c2 = 1./c1 , rats(c2)
      d1 = 0:4, d2 = 1:5, d3 = d1./d2 , rats(d3)
    
   6. n = 1:100;
      x = ( (-1).^(n+1) ) ./ (2*n - 1);
      y = sum(x)
    
   8. t = 1:0.2:2
      a = log(2 + t + t.^2)
      b = exp(t).*(1 + cos(3*t))
      c = cos(t).^2 + sin(t).^2  (all ones!)
      d = atan(t)
      e = cot(t)
      f = sec(t).^2 + cot(t) - 1
    
   12. t = 1790:2000;
      term = 1 + exp(-0.0313*(t - 1913.25));
      P = 197273000./term;
      plot(t,P)
      xlabel('year'), ylabel('population')
      P2020 = 197273000/(1 + exp(-0.0313*(2020 - 1913.25)))
    

Array exercises

   2. A = [ 2 4 1 ; 6 7 2 ; 3 5 9]
      x1 = A(1,:)
      y = A(end-1:end,:)
      c = sum(A)
      d = sum(A,2) or d = sum(A')'
      N = size(A,1), e = std(A)/sqrt(N)    
    
   5. A = [2 7 9 7 ; 3 1 5 6 ; 8 1 2 5]
      B = A(:,2:2:end)
      C = A(1:2:end,:)
      c = reshape(A,4,3) or c = A'  (they are different but are both 4x3)
      d = 1./A , rats(d)
      e = sqrt(A)
     
   6. randn('seed',123456789)
      F = randn(5,10);
      N = size(F,1)
      avg = mean(F)
      s = std(F)
      tscore = (avg - 0)./(s/sqrt(N))
      None were different at 90% LOC (all < 2.132).

Relational/Logical exercises

   4. x = [3 15 9 12 -1 0 -12 9 6 1]
      a = x, idxa = x > 0,     a(idxa) = 0
      b = x, idxb = ~rem(x,3), b(idxb) = 3
      c = x, idxc = ~rem(x,2), c(idxc) = 5*c(idxc) 
    
   5. x = 1:35;
      y = zeros(size(x));
      idx1 = x < 6;
      idx2 = (x >= 6) & (x < 20);
      idx3 = (x >= 20) & (x <= 35);
      y(idx1) = 2;
      y(idx2) = x(idx2) - 4;
      y(idx3) = 36 - x(idx3);
      
      disp([x(:) idx1(:) idx2(:) idx3(:) y(:)])
      plot(x,y,'o')
      

Loop constructs: The answers here provide one version of the solutions. Alternatives are possible and encouraged, especially where time and efficiency of the code is important.

   1. x = [1 8 3 9 0 1]
     
     a. total = 0;
        for j = 1:length(x)
           total = total + x(j);
        end
     b. runningTotal = zeros(size(x));
        runningTotal(1) = x(1);
        for j = 2:length(x)
           runningTotal(j) = runningTotal(j-1) + x(j);
        end
     c. s = zeros(size(x));
        for j = 1:length(x)
           s(j) = sin(x(j));
        end
     
   2. A = rand(4,7);
      [M,N] = size(A);
      for j = 1:M
         for k = 1:N
            if A(j,k) < 0.2
               A(j,k) = 0;
            else
               A(j,k) = 1;
            end
         end
      end
      
   3. x = [4 1 6], y = [6 2 7]   

      N = length(x);
      for j = 1:N
         c(j) = x(j)*y(j);
         for k = 1:N
            a(j,k) = x(j)*y(k);
            b(j,k) = x(j)/y(k);
            d(j,k) = x(j)/(2 + x(j) + y(k));
            e(j,k) = 1/min(x(j),y(k));
         end
      end
      c = sum(c);      % or use 1.a. loop

        
   4. These code snippets do the job but their repeated use is much
      more interesting.  An example is given for the first exercise.
      
      a. total = 0;            % initialize current sum (the test variable)
         count = 0;            % initialize the counter (output of the program)
         while total < 20      % loop until 20 is exceeded
            count = count + 1; % another loop repeat => another number added   
            x = rand(1,1);
            total = total + x; % modify the test variable!
         end
         disp(['It took ',int2str(count),' numbers this time.'])
         
         ------------------------------------------------------------
         
         To do this many times, place the above code in a for-loop.
         Some simple (though perhaps subtle) changes are needed wth respect
         to retaining the counts for each repeat.  Also, the summary has
         been changed from a single text message to a histogram.
         
         Nrep = 1000;   % collect 1000 repeats of the above code
         count = zeros(Nrep,1);
         for j = 1:Nrep
            total = 0;            % reset the test variable each repeat!!!
            while total < 20    
               count(j) = count(j) + 1; % use a vector to capture each result   
               total = total +  rand(1,1);
            end
         end
         hist(count,min(count):max(count))
         xlabel('Number of random numbers from U(0,1) added to make 20')
         ylabel('Count')
         title(['Histogram of results for ',int2str(Nrep),' repeats'])
         
         ------------------------------------------------------------
         
      b. count = 0;
         while 1                % infinite loop use
            count = count + 1;
            x = rand(1,1);                    % get a number
            if (x < 0.85) & (x > 0.8)   % check the value
               break                          % bail out if in selected range
            end
         end
         disp(['It took ',int2str(count),' numbers this time.'])
         
      c. count = 0;
         avg = 0;              % test variable
         while abs(avg - 0.5) > 0.01
            count = count + 1;
            
         % The following line is one way to update the average.
         % (count-1)*avg is the sum of the first count-1 numbers
         % and rand just adds another number.  Dividing by count
         % then gives the new average.
         
            avg = ((count-1)*avg + rand(1,1))/count;  % modify the test var.
         
         % There are other ways to do this and you are encouraged
         % to come up with them
         
         end
         disp(['It took ',int2str(count),' numbers this time.'])
      
   5. while 1     % use of an infinite loop
         TinF = input('Temperature in F: ');  % get input
         if isempty(TinF)                     % how to get out
            break
         end
         TinC = 5*(TinF - 32)/9;              % conversion
         disp(' ')
         disp([' ==> Temperature in C = ',num2str(TinC)])
         disp(' ')
      end
       

IF-block exercises

   1. n = 7   gives m = 8
      n = 9   gives m = -1
      n = -10 gives m = -11
      
   2. z = 1   gives w = 2
      z = 9   gives w = 0
      z = 60  gives w = sqrt(60)
      z = 200 gives w = 200
         
   3. T = 50 gives h = 0
      T = 15 gives h = 31
      T =  0 gives h = 1
      
   4. x = -1  gives y = -4
      x = 5   gives y = 20
      x = 30  gives y = 120
      x = 100 gives y = 400

   In this last exercise, y = 4x for any input!  Relational operations
   are subject to precedence and ordering just as arithmetical 
   operations.  The logical phrase a < x < b should be rendered as 
   the compound logical expression ((a < x) & (x < b)) in MATLAB.
      
   8. See the discussion under IF-block exercise 4, above.
  

[Back to main page] [Back to exercises page]
Comments? Contact Jim Maneval at maneval@bucknell.edu