Matlab subtracting matrix elements

让人想犯罪 __ 提交于 2019-12-02 23:18:30

问题


so i have this matrix

data =

 1
 3
 4
 3
 5
 2
 5

i need to get new data by subtracting the element like this

data2-data1
data3-data2
data4-data3
data5-data4
data6-data5
data7-data4
...
datan-data(n-1)

so from that data the output should be im =

 2
 1
-1
 2
-3
 3

i still trying to manipulate this code but got an error

clc
data=[1;3;4;3;5;2;5]
cnt=size(data,1)

for i=1:cnt;
    im=(data(i)-(data(i-1)));
end
im

回答1:


diff does what you want.

diff(data)

BUT if you want to continue with your approach, I imagine the error you get is related to data(i-1) cannot be defined when i = 1. Your loop should be 2:cnt.

Another method would be data(2:end) - data(1:end-1)



来源:https://stackoverflow.com/questions/42896839/matlab-subtracting-matrix-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!