Calculate difference of elements in a vector with grid
Show older comments
Hi,
For example, I have a variable named y = [1,4,7,3,9,5,2,8]. I want to get a return variable r1 = [6,-1,2,2,-7,3] and r2 = [2,5,-2,-1,-1] which are differences with grid=1 and grid=2. It seems that I can't use function diff() when there is a grid not equal to 1. Can anyone tell me how to implement these calculations? Many thanks.
Answers (1)
AR
on 26 Feb 2025
From my understanding of the question, for the variable y = [1, 4, 7, 3, 9, 5, 2, 8], the expected outputs are r1 = [6, -1, 2, 2, -7, 3] and r2 = [2, 5, -2, -1, -1], representing differences with grid sizes of 1 and 2, respectively.
As per the documentation for “diff()” function, it is intended to calculate differences between consecutive elements, which corresponds to a grid size of 1. When “diff(y, n)” is used, it computes the nth order difference, which is not simply a grid size of n. Instead, it repeatedly applies "diff()", calculating differences of differences, and so on.
Refer the below link to access the documentation for “diff()” function:
To achieve the desired result for a grid size of 2, use manual indexing that calculates the difference between elements which are two positions apart.
% Calculate r1 with grid=1 using diff()
r1 = diff(y);
% Calculate r2 with grid=2 using manual indexing
r2 = y(3:end) - y(1:end-2);
I hope this clarifies!
Categories
Find more on MATLAB 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!