Finding difference of array using alternative indexes
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Adam Danz
le 7 Juin 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.
Réponse acceptée
Adam Danz
le 7 Juin 2021
Modifié(e) : Adam Danz
le 7 Juin 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 commentaires
Adam Danz
le 9 Juin 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.
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!