Finding difference of array using alternative indexes
이전 댓글 표시
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
shane watson
2021년 6월 4일
shane watson
2021년 6월 4일
편집: shane watson
2021년 6월 4일
Adam Danz
2021년 6월 4일
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
2021년 6월 7일
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.
채택된 답변
추가 답변 (1개)
n = length(a) ;
iwant = (a(2:n)-a(1:n-1))./((2:n)-(1:n-1)) ;
Also have a look on geadient.
댓글 수: 4
shane watson
2021년 6월 4일
KSSV
2021년 6월 4일
Use gradient. You will get 1*24 dimension.
KSSV
2021년 6월 4일
iwant = gradient(a) ;
shane watson
2021년 6월 4일
편집: shane watson
2021년 6월 4일
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

