Calculate difference of elements in a vector with grid
조회 수: 3 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
답변 (1개)
AR
2025년 2월 26일
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!
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!