Row subtraction in matrix

I am trying to subtract each row in a matrix from the row after it. The function diff does x_{i} - x_{i+1}, I need to do x_{i}-x_{i-1}. I cannot find anything that will tell me how to do this. I am sure it is something simple that I am just overlooking.

3 件のコメント

James Tursa
James Tursa 2018 年 5 月 23 日
No. diff() does row{i}-row{i-1} just like you apparently want.
Stephen23
Stephen23 2018 年 5 月 23 日
The diff help states that for a matrix it returns
[X(2,:)-X(1,:); X(3,:)-X(2,:); ... X(p,:)-X(p-1,:)]
which seems to match what you asked for.
Ian Loveless
Ian Loveless 2018 年 5 月 23 日
Then I mistyped. Is there a way I can do row{i}-row{i+1}?

サインインしてコメントする。

回答 (1 件)

James Tursa
James Tursa 2018 年 5 月 23 日
編集済み: James Tursa 2018 年 5 月 23 日

0 投票

Just negate the usual diff() result. E.g.,
x = your matrix
result = -diff(x);

6 件のコメント

Ian Loveless
Ian Loveless 2018 年 5 月 23 日
That just gives me the negative of diff(), it does not subtract in the opposite direction.
James Tursa
James Tursa 2018 年 5 月 23 日
Really? Have you tried it?
Ian Loveless
Ian Loveless 2018 年 5 月 23 日
Yes I did. It is the same as my diff() matrix, except each value has "-" in front of it.
James Tursa
James Tursa 2018 年 5 月 23 日
編集済み: James Tursa 2018 年 5 月 23 日
So, there appears to be a disconnect of some sort with your description and what you want. Consider this:
>> x = randi(10,3,4)
x =
8 1 7 4
10 9 8 7
7 10 8 2
>> -diff(x)
ans =
-2 -8 -1 -3
3 -1 0 5
It certainly looks to me like the first row of the result is x_row1-x_row2 etc. Similarly for the second row of the result. So for the x shown above, what is the result that you want exactly if it isn't what I have shown?
Stephen23
Stephen23 2018 年 5 月 24 日
編集済み: Stephen23 2018 年 5 月 24 日
"It is the same as my diff() matrix, except each value has "-" in front of it."
That would be exactly correct then. The only difference between these
row(i)-row(i+1)
row(i)-row(i-1)
will be the sign. So if all were positive in the first case, then in the second case all would be negative.
Ian Loveless
Ian Loveless 2018 年 5 月 25 日
You are all correct, I apologize for my ignorance. I was looking at spacings instead of differences. Thank you for your help and patience.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

リリース

R2018a

タグ

質問済み:

2018 年 5 月 23 日

コメント済み:

2018 年 5 月 25 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by