-5

Everybody is told to exploit vectorised programmes such as MATLAB and use indexing instead of a for loop.

for e.g, in MATLAB, rather than setting all the element of a matrix to 0 in a double for loop, I could use M[1:N,1:N]=0;.

My question relates to whether this works sequentially? i.e, if I have some row vector v of size N, and I execute the following line

v[1:N-1]=v[2:N]

Then will updated values be used throughout, or does it take a "snapshot" of the vector, and paste that into the vector again in a shifted index?

I'd like it to do this sequentialy so that the values are updated from the bottom first and then used again for values above etc

phiver
  • 23,048
  • 14
  • 44
  • 56
  • 1
    I don't understand what you're asking. Used throughout what? – sco1 Aug 08 '16 at 13:41
  • Hi. Used throughout the remaining assigning of values. I'd like it to do the follwoign loop essentially: for I=1:N-1 v[i]=v[i+1] end But without the overhead cost of a for loop – Quant525 Aug 08 '16 at 13:44
  • I think the "snapshot" analogy is close enough. But an operation is an operation – marco wassmer Aug 08 '16 at 13:46
  • If you're performing repeated operations you need to loop, I'm still not understanding what you're trying to accomplish or how the above syntax removes the need to use a loop. – sco1 Aug 08 '16 at 13:49
  • 1
    For your example, it doesn't matter whether it's looped or not, so... – Frank Aug 08 '16 at 13:51
  • It does? I want it to use the new values as they appear, as they are updates, as opposed to only using the old values. – Quant525 Aug 08 '16 at 14:07
  • You're overwriting the current value with the next value sequentially. The end result is the same as taking the entire V[2:N] and overwriting its values onto V[1:(N-1)]. There are cases where iteration is necessary, but this does not look like one of them. – Frank Aug 08 '16 at 14:25
  • Sorry my mistake. The loop should run from N-1:1. This way, I'd like updated values to be used Is there any efficient way of doing this? – Quant525 Aug 08 '16 at 14:38
  • I think your question would be much better off if you explained *specifically* what you're trying to do. Your abstraction of the problem is making less sense as you explain it more. – sco1 Aug 08 '16 at 15:03

1 Answers1

0

It works as though everything on the right hand side happens before anything on the left hand side, effectively doing the "snapshot" thing but with probably better memory efficiency. In reality, it may loop through or it may take a "snapshot", but due to abstraction you don't really need to know or care about that.

So the result would be something like as follows:

v=[1 2 3 4 5 6];
v[1:5]=v[2:6];
disp(v)

    v =
      [2 3 4 5 6 6]

Is that what you want?

  • Many thanks for your reply. Makes sense. I actually want it to use updated values. So I want it to act like its is a loop, using the new value in each iteration, but be more effieicnt. – Quant525 Aug 08 '16 at 13:48