在MatLab中与diff相反

时间:2015-04-08 01:38:15

标签: matlab

如果我有矩阵x=[x(1) x(2) x(3) ... x(n-1) x(n],则diff(x)会给出 [x(2)-x(1) x(3)-x(2) ... x(n)-x(n-1)]。是否有这样的添加功能,结果将是[x(1)+x(2) x(2)+x(3) ... x(n-1)+x(n)]

4 个答案:

答案 0 :(得分:5)

您可以尝试简单地执行

x(2:end) + x(1:end-1)

答案 1 :(得分:4)

[1 1]

对话
y = conv(x, [1 1], 'valid');

答案 2 :(得分:3)

没有内置函数,但如果你需要经常使用它,那么创建一个单独的函数或像这样的匿名函数

%// Anonymous function - can be used inside the script alone any no. of times
summ = @(x) x(2:end) + x(1:end-1);   %// Answer by nneonneo

测试运行:

>> A = randi([1,5],1,5)

A =
 2     3     4     5     5

>> summ(A)

ans =
 5     7     9    10

答案 3 :(得分:0)

与Matlab中的差异相反的是cumsum

示例:

>> A = randi([1,5],1,5)

A =

     1     3     5     2     1

>> B = diff(A)

B =

     2     2    -3    -1

>> C = cumsum([A(1) B])

C =

     1     3     5     2     1