Operations on consecutive elements of a vector

Imagine there is a vector C with n elements, c(i). Without using a loop I would like to a have new vector D whose elements are:
d(i)= c(i) if i=1
d(i)= c(i-1)-c(i) if 1<i<n
d(i)= -c(i) if i=n
I do not care about the first and last elements which I could add by concatenation, but generally I am looking for a way to perform mathematical operations on consecutive elements of a vector without using a loop. Is this possible?

 Akzeptierte Antwort

dpb
dpb am 8 Feb. 2016

0 Stimmen

If'en I interprets your requirements correctly...
d=[c(1) diff(c(1:end-1)) -c(end)];
Example:
>> c=randi(10,1,5)
c =
9 9 4 7 3
>> d=[c(1) diff(c(1:end-1)) -c(end)]
d =
9 0 -5 3 -3
>>

6 Kommentare

Stephen23
Stephen23 am 8 Feb. 2016
Bearbeitet: Stephen23 am 8 Feb. 2016
The question specifies the difference as " c(i-1)-c(i)" rather than the c(i)-c(i-1) that diff supports. A simple minus resolves the problem:
d = [c(1),-diff(c(1:end-1)),-c(end)]
dpb
dpb am 8 Feb. 2016
I had it that way first and decided probably was misstated by OP... :)
Saeid
Saeid am 9 Feb. 2016
Thank you both. Your answers saved me a lot of time again!
Saeid
Saeid am 9 Feb. 2016
By the way, what if I want to perform some other basic operation on consecutive elements, e.g. adding, multiplication etc.?
dpb
dpb am 9 Feb. 2016
Bearbeitet: dpb am 10 Feb. 2016
All depends on what the operation(s) is(are); sometimes it's easily vectorized, other times "not so much". filter can do many operations but not all. See
help datafun % for list to give some ideas on what's builtin
After that, it's mostly just thinking about the operations and using "time in grade" to apply Matlab syntax to the particular case.
Oh, and it helps if you're reasonably fluent in matrix algebra and have some knowledge of some of the special properties of matrices so that can recognize when magic occurs...
ADDENDUM
Oh, I am not into image processing so didn't think of it originally, but there's blockproc in that toolbox or, if you don't have access to it a submission in the File Exchange (not tried)... Apply function on subsets of array>
Saeid
Saeid am 3 Mär. 2016
Thnaks a lot!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 8 Feb. 2016

Kommentiert:

am 3 Mär. 2016

Community Treasure Hunt

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

Start Hunting!

Translated by