Finding difference of array using alternative indexes
4 views (last 30 days)
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
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
Adam Danz
on 7 Jun 2021
Edited: Adam Danz
on 7 Jun 2021
The loss of 1 value when differentiating with diff(x,1) is the expected behavior. This function computes the difference between adjacent values in a matrix [a b c d] and there is n-1 comparisons.
Comparison between gradient and diff
y = exp([1:.1:3]);
d = diff(y);
g = gradient(y);
size(y)
size(d)
size(g)
x = 1:numel(y)
hold on
plot(x(2:end),d,'b-','DisplayName','diff')
plot(x,g,'r-','DisplayName','gradient')
legend
2 Comments
Adam Danz
on 9 Jun 2021
I need to know more about your goal. In your original question, the indexing error was caused by the loss of 1 value due to differentiating using diff(). Maybe you don't need to differentiate. Maybe you need to differentiate using a different method. Or maybe what you're doing is fine and you need to understand the output.
See Also
Categories
Find more on Creating and Concatenating Matrices 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!