Finding difference of array using alternative indexes
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
Adam Danz
2021-6-7
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.
采纳的回答
Adam Danz
2021-6-7
编辑:Adam Danz
2021-6-7
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 个评论
Adam Danz
2021-6-9
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!