I read MATLAB diff.m readme, still couldn't figure out the following:
a = [1 2 3]'
b = [3 2 1 4; 1 1 1 5; 5 5 5 6]
diff([a b]') =
2 -1 2
-1 0 0
-1 0 0
3 4 1
what rule is MATLAB applying here? does MATLAB apply different rule if one of the matrices (i.e. a or b) is logical matrix? or both a and b are logical matrix?
CodePudding user response:
a =
[1
2
3]
So,
[a b] =
[ 1 3 2 1 4
2 1 1 1 5
3 5 5 5 6 ]
and thus
[a b]' =
[ 1 2 3
3 1 5
2 1 5
1 1 5
4 5 6 ]
and then diff takes the differences along the first dimension whose size is not 0 (i.e. down each column). This gives the result
diff([a b]') =
[ 2 -1 2
-1 0 0
-1 0 0
3 4 1 ].
CodePudding user response:
MATLAB applies the same rule regardless of the input matrices. Run your code line-by-line in the command window and see.
a
and b
are like this:
>> a = [1 2 3]'
a =
1
2
3
>> b = [3 2 1 4; 1 1 1 5; 5 5 5 6]
b =
3 2 1 4
1 1 1 5
5 5 5 6
then [a b]'
:
>> [a b]'
ans =
1 2 3
3 1 5
2 1 5
1 1 5
4 5 6
Now apply the diff
rule on this as follows:
[ row 2 - row 1 ]
[ row 3 - row 2 ]
[ row 4 - row 3 ]
[ row 5 - row 4 ]
you will get
>> diff([a b]')
ans =
2 -1 2
-1 0 0
-1 0 0
3 4 1