Function "diff" and the loss of an element in the array (2024)

421 views (last 30 days)

Show older comments

Bryan Ambrósio on 13 Sep 2023

  • Link

    Direct link to this question

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array

  • Link

    Direct link to this question

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array

Commented: dpb on 14 Sep 2023

Accepted Answer: Torsten

I have an issue with MATLAB, specifically related to a "diff" operation that is causing the loss of an element. The "diff" function in MATLAB is used to calculate the differences between consecutive elements in an array or matrix. I am using this function to calculate the derivate of an array.

It is clear to me that the resulting vector must have one less element. However, I need to perform the "diff" operation twice on the same array (resulting in an array with two less elements), and the issue I'm facing is that I don't know whether the vector is losing an element at the beginning or at the end. Initially, I thought it might be at the beginning. But when I compare the result of this operation with a reference value, it seems to be shifted on the axis. How can I be sure of this?

PS: It really makes a difference in my implementation.

1 Comment

Show -1 older commentsHide -1 older comments

Stephen23 on 13 Sep 2023

Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2884621

  • Link

    Direct link to this comment

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2884621

"... the issue I'm facing is that I don't know whether the vector is losing an element at the beginning or at the end."

Neither: differences are between the elements of your vector, not at the same locations as them.

Sign in to comment.

Sign in to answer this question.

Accepted Answer

Torsten on 13 Sep 2023

  • Link

    Direct link to this answer

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#answer_1309386

  • Link

    Direct link to this answer

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#answer_1309386

Use "gradient" if you don't want to loose elements:

https://uk.mathworks.com/help/matlab/ref/gradient.html

2 Comments

Show NoneHide None

William Rose on 13 Sep 2023

Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2884711

Edited: William Rose on 13 Sep 2023

Open in MATLAB Online

I didn't know about gradient. Thanks @Torsten !

t=0:7; x=t.^3;

dxdtD=diff(x); d2xdt2D=diff(diff(x));

dxdtG=gradient(x); d2xdt2G=gradient(gradient(x));

disp(x); disp(dxdtG); disp(d2xdt2G)

0 1 8 27 64 125 216 343 1 4 13 28 49 76 109 127 3.0000 6.0000 12.0000 18.0000 24.0000 30.0000 25.5000 18.0000

@Bryan Ambrósio, compare the results from gradient() to the theoretical results for this signal, and to the results using diff(). An advantage of gradient() is that it gives estimates at the same locaitons as the sample locations, including at the edges. But you may not like its estimates at the edges. Your call.

legstr={'theo','Diff','Gradient'};

subplot(211);

plot(t,3*t.^2,'-g',t(1:end-1)+.5,dxdtD,'gx',t,dxdtG,'go');

ylabel('dx/dt'); grid on;

legend(legstr,'Location','best')

subplot(212);

plot(t,6*t,'-b',t(2:end-1),d2xdt2D,'bx',t,d2xdt2G,'bo');

ylabel('d^2X/dt^2'); xlabel('Time'); grid on;

legend(legstr,'Location','best')

Function "diff" and the loss of an element in the array (5)

Walter Roberson on 13 Sep 2023

Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2884726

  • Link

    Direct link to this comment

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2884726

And gradient allows you to specify the spacing between elements, which is important for getting the right scale on the derivatives.

Sign in to comment.

More Answers (2)

dpb on 13 Sep 2023

  • Link

    Direct link to this answer

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#answer_1309366

  • Link

    Direct link to this answer

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#answer_1309366

Open in MATLAB Online

diff is defined as x(i+1)-x(i) for i=2:numel(x). But, MATLAB arrays are always 1-based so the result of x(2)-x(1) is in the first location of the result vector. You don't really "lose" anything, but the location of the nth position corresponding to the initial vector does move down each successive operation...

Easy enough to illustrate numerically...

>> V=randi(20,1,10)

V =

7 6 13 9 10 10 19 2 6 9

>> dV1=diff(V)

dV1 =

-1 7 -4 1 0 9 -17 4 3

>> dV2=diff(dV1)

dV2 =

8 -11 5 -1 9 -26 21 -1

>>

Oftentimes it is convenient for coding purposes to prepend to the result to maintain the same length;

dV1=[nan diff(V)];

for example.

4 Comments

Show 2 older commentsHide 2 older comments

Steven Lord on 13 Sep 2023

Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2884831

  • Link

    Direct link to this comment

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2884831

Open in MATLAB Online

And note that you can call diff with two or three inputs to avoid having to call diff with one input repeatedly.

V=randi(20,1,10)

V = 1×10

17 20 7 4 18 19 19 11 7 8

dV1=diff(V)

dV1 = 1×9

3 -13 -3 14 1 0 -8 -4 1

dV2=diff(dV1)

dV2 = 1×8

-16 10 17 -13 -1 -8 4 5

dV2_anotherWay = diff(V, 2, 2)

dV2_anotherWay = 1×8

-16 10 17 -13 -1 -8 4 5

isequal(dV2, dV2_anotherWay)

ans = logical

1

I would advise using the three input syntax to avoid the case where you accidentally reduce the array to size 1 in the dimension over which your calls have been operating and start operating on a different dimension without intending to do so.

M = magic(4)

M = 4×4

16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1

for k = 1:4

M = diff(M)

end

M = 3×4

-11 9 7 -5 4 -4 -4 4 -5 7 9 -11

M = 2×4

15 -13 -11 9 -9 11 13 -15

M = 1×4

-24 24 24 -24

M = 1×3

48 0 -48

Did you expect the final M to have fewer columns than the original M?

M = magic(4)

M = 4×4

16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1

M2 = diff(M, 4, 1)

M2 = 0×4 empty double matrix

Stephen23 on 14 Sep 2023

Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2885191

  • Link

    Direct link to this comment

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2885191

"...but the location of the nth position corresponding to the initial vector does move down each successive operation..."

This explanation, like the original question, confuses data with indices.

dpb on 14 Sep 2023

Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2885851

  • Link

    Direct link to this comment

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2885851

I disagree @Stephen23; it simply notes that owing to the size differential, the indices to the locations of the original data are numerically lower than those to the original data from which the difference was computed to address the specifics of the original question as to which difference is stored where.

Of course, there are no other differences available to be stored, but that's somewhat different... :)

dpb on 14 Sep 2023

Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2885861

  • Link

    Direct link to this comment

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#comment_2885861

Yeah, @Steven Lord, I thought about adding in the alternate syntax but opted for brevity to keep to the original Q? only...sometimes one might need both differences in which case the three argument version doesn't help so much; you've got two calls either way.

I've thought of (but have never actually submitted it as formal enhancment request) it might be a worthwhile option to have a flag to return an array of successive differences as an alternative to the one n-th difference -- the problem and argument against being it makes it hard to deal with the higher dimension cases other than vector inputs.

Sign in to comment.

William Rose on 13 Sep 2023

  • Link

    Direct link to this answer

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#answer_1309381

  • Link

    Direct link to this answer

    https://www.mathworks.com/matlabcentral/answers/2020526-function-diff-and-the-loss-of-an-element-in-the-array#answer_1309381

Edited: William Rose on 13 Sep 2023

Open in MATLAB Online

@Bryan Ambrósio,

[edit: changed the code for plotting d2xdt2. The plotted result is unchanged, but the new verison of the code is more robust, because it will put d2xdt2 at the correct horizontal location, even if delta T is not unity.]

You can answer your own question by experiment.

t=0:1:7; x=t.^3;

dxdt=diff(x); d2xdt2=diff(diff(x));

disp(x); disp(dxdt); disp(d2xdt2)

0 1 8 27 64 125 216 343 1 7 19 37 61 91 127 6 12 18 24 30 36

You can see that the times associated with the second derivative are offset by 1 sample at the beginning and by 1 at the end. Plot the results as shown:

subplot(311); plot(t,x,'-r.'); ylabel('X'); grid on

subplot(312); plot(t(1:end-1)+.5,dxdt,'-g.'); ylabel('dX/dt'); grid on

subplot(313); plot(t(2:end-1),d2xdt2,'-b.');

ylabel('d^2X/dt^2'); xlabel('Time'); xlim([0 7]); grid on

Function "diff" and the loss of an element in the array (13)

The plots agree with the analytical solution for the first and second derivatives of x=t^3.

0 Comments

Show -2 older commentsHide -2 older comments

Sign in to comment.

Sign in to answer this question.

See Also

Categories

MATLABGraphics

Find more on Graphics in Help Center and File Exchange

Tags

  • diff function
  • loss of element

Products

  • MATLAB

Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.


Function "diff" and the loss of an element in the array (14)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom(English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本Japanese (日本語)
  • 한국Korean (한국어)

Contact your local office

Function "diff" and the loss of an element in the array (2024)
Top Articles
Logs Preview - en
7 Best Ways to Invest £100k in 2024
Wizard Build Season 28
Www.politicser.com Pepperboy News
Seth Juszkiewicz Obituary
Savage X Fenty Wiki
Persona 4 Golden Taotie Fusion Calculator
Belly Dump Trailers For Sale On Craigslist
Chile Crunch Original
Love In The Air Ep 9 Eng Sub Dailymotion
Costco Gas Foster City
Apne Tv Co Com
Nissan Rogue Tire Size
Mflwer
Costco Gas Foster City
Keurig Refillable Pods Walmart
라이키 유출
Aldi Bruce B Downs
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Melendez Imports Menu
Sister Souljah Net Worth
Webworx Call Management
Divide Fusion Stretch Hoodie Daunenjacke für Herren | oliv
Aes Salt Lake City Showdown
Roseann Marie Messina · 15800 Detroit Ave, Suite D, Lakewood, OH 44107-3748 · Lay Midwife
Obituaries, 2001 | El Paso County, TXGenWeb
Gopher Carts Pensacola Beach
Lesson 1.1 Practice B Geometry Answers
Die wichtigsten E-Nummern
Dtlr On 87Th Cottage Grove
Tire Pro Candler
Gridwords Factoring 1 Answers Pdf
Ofw Pinoy Channel Su
Kltv Com Big Red Box
Wcostream Attack On Titan
Craigslist Ludington Michigan
Giantess Feet Deviantart
Free Robux Without Downloading Apps
3496 W Little League Dr San Bernardino Ca 92407
Craigslist Free Manhattan
877-292-0545
Final Jeopardy July 25 2023
Easy Pigs in a Blanket Recipe - Emmandi's Kitchen
Nid Lcms
Directions To Cvs Pharmacy
Tgirls Philly
Where Is Darla-Jean Stanton Now
Southwind Village, Southend Village, Southwood Village, Supervision Of Alcohol Sales In Church And Village Halls
Bob Wright Yukon Accident
Www Extramovies Com
Texas Lottery Daily 4 Winning Numbers
Latest Posts
Article information

Author: Margart Wisoky

Last Updated:

Views: 6486

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Margart Wisoky

Birthday: 1993-05-13

Address: 2113 Abernathy Knoll, New Tamerafurt, CT 66893-2169

Phone: +25815234346805

Job: Central Developer

Hobby: Machining, Pottery, Rafting, Cosplaying, Jogging, Taekwondo, Scouting

Introduction: My name is Margart Wisoky, I am a gorgeous, shiny, successful, beautiful, adventurous, excited, pleasant person who loves writing and wants to share my knowledge and understanding with you.