MATLAB: Difference

diff()MATLABvectors

I have vector A =
Columns 1 through 5
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Columns 6 through 10
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Columns 11 through 15
1.4602 1.4606 1.4609 1.4612 1.4615
0 0 0 0 0
0 0 0 0 0
Columns 16 through 20
1.4619 1.4622 1.4625 1.4629 1.4632
0 0 0 0 0
0 0 0 0 0
Column 21
1.4635
0
0
Why does
diff(A) =
ans =
Columns 1 through 5
0 0 0 0 0
0 0 0 0 0
Columns 6 through 10
0 0 0 0 0
0 0 0 0 0
Columns 11 through 15
-1.4602 -1.4606 -1.4609 -1.4612 -1.4615
0 0 0 0 0
Columns 16 through 20
-1.4619 -1.4622 -1.4625 -1.4629 -1.4632
0 0 0 0 0
Column 21
-1.4635
0
diff(A(1,:)) =
ans =
Columns 1 through 5
0 0 0 0 0
Columns 6 through 10
0 0 0 0 1.4602
Columns 11 through 15
0.0003 0.0003 0.0003 0.0003 0.0003
Columns 16 through 20
0.0003 0.0003 0.0003 0.0003 0.0003
give different result?

Best Answer

If I remember correctly, diff works across the first non-singleton dimension. So diff(A) works across columns and diff(A(1, :)) works across rows.
x = [1,2,3; 4,5,6];
diff(x, [], 1)
ans =
3 3 3
diff(x, [], 2)
ans =
1 1
1 1