1

On matlab: I have a vector P. I want to store the values P(k+1) - P(k) in a new vector M. I can do it with a for loop, but is there anything more efficient (I have a huge vector).

bigTree
  • 2,103
  • 6
  • 29
  • 45
  • 1
    A for loop will be nearly as efficient as anything else, since under the hood any other method would have to be a similar construct. – Paul Draper Oct 29 '13 at 07:09
  • 4
    U can use [diff](http://www.mathworks.com.au/help/matlab/ref/diff.html) – Marcin Oct 29 '13 at 07:10
  • @PaulDraper there is a built in fuction for this, `diff`, which I imagine would be quicker as it is probably written and optimized in `c` rather than `Matlab`. But I could be wrong. It's certainly more readable. – Dan Oct 29 '13 at 07:12
  • @PaulDraper - In MATLABland, that is very much the opposite of conventional wisdom, putting it gently. It is rare that a for loop will beat a properly vectorized or builtin function for the same task. – chappjc Oct 29 '13 at 07:19
  • You sold me on readability. – Paul Draper Oct 29 '13 at 07:48
  • about efficiency read: http://stackoverflow.com/questions/7569368/for-loop-vs-vectorization-in-matlab - tl;dr: for loops no longer mean bad performance in matlab – bdecaf Oct 29 '13 at 13:04
  • 1
    @bdecaf - Somewhat ironically, I have made your same point several times at SO, but the JIT accelerator is unpredictable and still usually not as good as equivalent vectorized operations. I made the comment above because even with these improvements, the first thought should still not be a "for loop will be nearly as efficient as anything else". That is a _wildly_ misleading statement. Notice that I did not say for loops would be bad, because they aren't any more, as you pointed out. Admittedly, this way of thinking seems to be going the way of the dinosaur, and that suits me just fine. :) – chappjc Oct 29 '13 at 17:54
  • Just for fun reading, [here is a fantastic investigation/discusion on mathworks.com](http://www.mathworks.com/matlabcentral/answers/54522) regarding JIT acceleration of loops started recently by angainor. I wonder what happened to him... – chappjc Oct 29 '13 at 18:16

3 Answers3

1

As Marcin said, use diff. For a 1D vector, diff(a). For the diff along dim 1, diff(a,[],1). Along dim 2, use diff(a,[],2).

chappjc
  • 30,359
  • 6
  • 75
  • 132
1

Simple solution

Difference = V(2:n) - V(1:n-1) where n is the size of the Vector V;

n = size(V,1);

Thomas Carlton
  • 5,344
  • 10
  • 63
  • 126
-1

I think it might be easier to just make your vector P, then duplicate it and shift it a bit. If you make the vector Pk (your regular P vector, but padded above) and then make the Pk+1 (let's call it Pkp1) and pad it below.

Pk   = [0 P];
Pkp1 = [P 0];
M    = Pkp1 - Pk

This makes it an elementwise matrix operation, which is always faster than looping. You can change to 0 padding off course if your recursive algorithm so demands.

I hope this helps you a bit. Martin

Martin
  • 66
  • 3