Finding difference of array using alternative indexes
Show older comments
Hello everyone,
I hope you're doing, I've simple question I've array (1, 24), now I want to findout the difference and divide, like [element1-element2 element2- element3 element3-element4...............element24-element23], what I did as follows
for i=1:24
a=1x24
%first case
a1(i)=a(i)-a(i+1)./i-(i+1),
% Second case
a1(i)=a(i)-a(i-1)./i-(i-1)
end
However, it is clear the index causing error (first case: Index exceeds the number of array elements (24). second case: Array indices must be positive integers or logical values.)
, could you please help me out in this situation.
6 Comments
shane watson
on 4 Jun 2021
Stephen23
on 4 Jun 2021
shane watson
on 4 Jun 2021
Edited: shane watson
on 4 Jun 2021
Adam Danz
on 4 Jun 2021
Consider a 1x4 vector x,
x = [2 5 3 6]
The difference you describe would be
d = [2-5, 5-3, 3-6]
or
d = [-3 2 -3]
which is a 1x3 vector. So your loop must either be
for i = 2:numel(x)
or
for i = 1:numel(x)-1
shane watson
on 7 Jun 2021
Adam Danz
on 7 Jun 2021
I'm trying to show you that the loss of one value when numerically differentiating is not a problem - it's exactly the expected behavior. Carefully look at my previous comment again to understand why you're losing a value.
I'll add an answer to suggest an alternative.
Accepted Answer
More Answers (1)
n = length(a) ;
iwant = (a(2:n)-a(1:n-1))./((2:n)-(1:n-1)) ;
Also have a look on geadient.
4 Comments
shane watson
on 4 Jun 2021
KSSV
on 4 Jun 2021
Use gradient. You will get 1*24 dimension.
KSSV
on 4 Jun 2021
iwant = gradient(a) ;
shane watson
on 4 Jun 2021
Edited: shane watson
on 4 Jun 2021
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
