Matlab gets basic arithmetic completely wrong!

조회 수: 4 (최근 30일)
Petter Stefansson
Petter Stefansson 2018년 8월 11일
댓글: Petter Stefansson 2018년 8월 11일
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.

채택된 답변

Dimitris Kalogiros
Dimitris Kalogiros 2018년 8월 11일
편집: Dimitris Kalogiros 2018년 8월 11일
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
Petter Stefansson
Petter Stefansson 2018년 8월 11일
Oh wow, how did I manage to miss that. That’s embarrassing. Thank you spotting the NaNs!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Distribution Plots에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by