Given:
A=[1,3,5,2,6,1];
Is there a function where I can get a difference of first and following cell in above matrix?
For example, output should be = 1-3, 3-5, 5-2,2-6,6-1 = -2,-2,3,-4,5
Finally, is there a way to sum the entire value in the matrix?
Thanks

 採用された回答

Stephen23
Stephen23 2020 年 10 月 28 日

0 投票

>> -diff(A)
ans =
-2 -2 3 -4 5
>> sum(-diff(A))
ans =
0

3 件のコメント

Daniel Lee
Daniel Lee 2020 年 10 月 28 日
thanks. could you please explain why u put negative sign before diff?
Stephen23
Stephen23 2020 年 10 月 28 日
編集済み: Stephen23 2020 年 10 月 28 日
"could you please explain why u put negative sign before diff?"
Because a-b == -(b-a)
In your question you specified that you wanted "...output should be = 1-3...", which is A(1)-A(2). By definition diff returns A(2)-A(1), but simply negating that gives what you asked for: A(1)-A(2) == -(A(2)-A(1))
Another option would be to use indexing and subtraction (but is likely to be less efficient than diff):
>> A = [1,3,5,2,6,1];
>> A(1:end-1)-A(2:end)
ans =
-2 -2 3 -4 5
>> -diff(A)
ans =
-2 -2 3 -4 5
Daniel Lee
Daniel Lee 2020 年 10 月 28 日
ahhh. i see. thanks

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeOperators and Elementary Operations についてさらに検索

製品

リリース

R2020a

タグ

質問済み:

2020 年 10 月 28 日

コメント済み:

2020 年 10 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by