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!

