Finding difference of array using alternative indexes
조회 수: 4 (최근 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!