Subtracting one row from a previous row in a single column of n long data
Show older comments
I have a single column of data that is n long and I want to be able to subtract the second row in that column by the first and have that pattern repeat. (third row subtracted by the second, fourth row subtracted by the thrid and so on).
Ex:
1
5
6
7
4
3
I would like to be able to have a code that does 5-1, 6-5, 7-6, 4-7, 4-3.
I am pretty new to MatLab so if I am using incorrect terminology or my question is confusing in any way please let me know.
Accepted Answer
More Answers (1)
a = [1
5
6
7
4
3];
diff(a)
7 Comments
Jacob Allen
on 5 Feb 2022
Voss
on 5 Feb 2022
That error's not coming from diff() but probably a subsequent line and is due to the fact that the output from diff() is an array that is smaller than the input to diff(), in this case smaller by 1.
Caution: when you use diff() with only one parameter, then diff() is taken along the first non-singular dimension, which might not be along the columns.
A = magic(5);
for K = [3 2 1]
B = A(1:K,:)
diff(B)
end
Notice that ans has 5 columns for K = 3 and K = 2, but suddenly has 4 columns for K = 1 ? Because for K = 1, the first non-singular dimension of B is the second dimension.
As you had distinctly requested to take differences between rows, in my Answer I showed the form that takes differences between rows even if there is only one row: diff(A, [], 1)
Jacob Allen
on 6 Feb 2022
Voss
on 6 Feb 2022
Like I said, "due to the fact that the output from diff() is an array that is smaller than the input to diff(), in this case smaller by 1."
So, say bulkdensity and depth are each of size 100-by-1, then N will be of size 99-by-1, so you can't do an element-wise operation (.*) on a vector with 100 elements and a vector with 99 elements. Or, restated in terms of what your data represent: if you have data at certain depths, say 100 of them, then you'll get 99 depth intervals between those depths, so something's gotta give...
You have to decide whether each bulkdensity data point should be associated to the top of its depth interval (and use bulkdensity(1:end-1) in your calculation) or the bottom (use bulkdensity(2:end)). In either case you have to discard a bulkdensity sample because there are 1 more bulkdensity values than there are depth intervals.
This type of thing comes up a lot, so there's a name for it: https://en.wikipedia.org/wiki/Off-by-one_error#Fencepost_error
Jacob Allen
on 6 Feb 2022
Walter Roberson
on 10 Feb 2022
It is common that gradient() should be used instead of diff()
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!