MATLAB Answers

Matlab gets basic arithmetic completely wrong!

3 views (last 30 days)
I just had a Matlab experience that made me question everything.
I have two vectors: v1 and v2. Both are of length 10 000 and in double-precision. If I plot them, they look like this:
Clearly, these two vectors are very different - one contains values as high as 30 while the other one contains mostly zeros and maxes out at around 6.8.
So far so good. But now when I plot the difference between the two vectors ( v1-v2) I get this:
And if I calculate the maximum absolute difference between the two:
max(abs(v1-v2))
I get 4.4409e-15! What is going on here!?
Clearly the maximum absolute difference should be around 30, not in the order of e-15 something. So what am I facing here? Is it:
  • My Matlab installation that is broken
  • My system that is broken and can’t do arithmetic correctly
  • My brain that is broken and the result are correct
This is the code I use to replicate the results, and I’m attaching a .mat file with the v1 and v2 vectors:
% Load v1 and v2
load('TwoStrangeVectors.mat')
% Plot vector 1
subplot(3,1,1)
plot(v1)
title('vector #1'), xlim([1 10000])
% Plot vector 2
subplot(3,1,2)
plot(v2)
title('vector #2'), xlim([1 10000])
% Plot vector 1 minus vector 2
subplot(3,1,3)
plot(v1 - v2)
title('vector #1 - vector #2'), xlim([1 10000])
I’m using Matlab 2018a on Windows 10 using a i7-8700K processor.

  0 Comments

Sign in to comment.

Accepted Answer

Dimitris Kalogiros
Dimitris Kalogiros on 11 Aug 2018
Edited: Dimitris Kalogiros on 11 Aug 2018
Vector v1 is corrupted. It contains "NaN" at the most of its values. Matlab subtracts only at positions where v1 contains valid numbers.
Run the following script, to see what I mean:
close all;
clear all
% Load v1 and v2
load('TwoStrangeVectors.mat')
%define an area of interest
t=2000:2030;
% Plot vector 1
subplot(3,1,1)
plot(t,v1(t),'-ro'); zoom on; grid on;
title('a piece of vector #1') % xlim([1 10000])
% Plot vector 2
subplot(3,1,2)
plot(t,v2(t),'-b*'); zoom on; grid on;
title('a piece of vector #2') %xlim([1 10000])
% Plot vector 1 minus vector 2
subplot(3,1,3)
plot(t, v1(t)-v2(t), '-ms'); zoom on; grid on;
title(' a piece of vector #1 - vector #2')

  1 Comment

Petter Stefansson
Petter Stefansson on 11 Aug 2018
Oh wow, how did I manage to miss that. That’s embarrassing. Thank you spotting the NaNs!

Sign in to comment.

More Answers (0)

Sign in to answer this question.