Matlab gets basic arithmetic completely wrong!
2 次查看(过去 30 天)
显示 更早的评论
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/193613/image.png)
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/193615/image.png)
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 个评论
采纳的回答
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')
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!