Interesting Programming Errors

  1. The array "odd_values" may be the same length as "even_values", or it may be 1 less. If it is shorter, we need to append a zero to make them the same size.
    % Make sure arrays are same length
    if (length(odd_values) < length(even_values))
       odd_values(length(odd_values+1)) = 0;
    After running the above, we get an error because odd_values is STILL 1 value short of even_values. Here is the fix:
    % Make sure arrays are same length
    if (length(odd_values) < length(even_values))
       odd_values(length(odd_values)+1) = 0;
    It adds 1 to the length, instead of adding 1 to each value of "odd_values".
  2. This code is supposed to calculate interest, but the amount to repay gets out-of-control.
    x = 0.0639; % interest
    n = 10;
    principal = 165000;
    monthly_payment = 1031.00;
    for yr=1:30
       for mo=1:12
         for i=1:n
           compound = compound*(1+ x/(n*12));
         disp(sprintf('%10.2f', compound));
         % every month, we deduct the payment
         compount = compound - monthly_payment;
    The problem? That should be "compound = compound - monthly_payment;".
Michael Weeks, copyright 2006, 2009