Subtract according to the values in another column

1 回表示 (過去 30 日間)
Aragorn23
Aragorn23 2019 年 7 月 11 日
編集済み: Matt J 2019 年 7 月 11 日
Hi everyone,
I have two columns, with the same amount of elements.
C1 = 1-1-1-1-1-2-2-2-2-2-2-3-3-3-4-4-4-4
C2 = 5-10-12-35-3-1-4-26-5-11-12-8-2-22-8-2-5-7
I would like to subtrate the values of C2 according to C1(e.g., 3-5; 12-1; 22-8; 7-8), and present the results like that:
1: -2;
2: 11
3: 14
4: -1
How can I do that?
  3 件のコメント
Guillaume
Guillaume 2019 年 7 月 11 日
編集済み: Guillaume 2019 年 7 月 11 日
Like Geoff, I don't understand how the result is obtained. Pleas clarify
And, please, use valid matlab notation in your examples, so we can just copy/paste it into matlab. With the way you've written it it's difficult to know which element of C1 correspond to which element of C2
C1 = [1 1 1 1 1 2 2 2 2 2 2 3 3 3 4 4 4 4] %this is valid matlab syntax
C2 = [5 10 12 35 3 1 4 26 5 11 12 8 2 22 8 2 5 7] %We can just copy/paste that into matlab
edit: And now that I've written it in a readable way, it's clear that what you want is last-first for each index. Hence, the importance of formatting your post properly.
Aragorn23
Aragorn23 2019 年 7 月 11 日
編集済み: Aragorn23 2019 年 7 月 11 日
Maybe I didn't present the data in the right way.
C1 C2
1 5
1 10
1 12
1 35
1 3
2 1
2 4
2 26
2 5
2 11
2 12
3 8
3 2
3 22
4 8
4 2
4 5
4 7
C1 = [1 1 1 1 1 2 2 2 2 2 2 3 3 3 4 4 4 4];
C2 = [5 10 12 35 3 1 4 26 5 11 12 8 2 22 8 2 5 7];
I would like to subtract the first and the last element of C2 according to C1.

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

採用された回答

Guillaume
Guillaume 2019 年 7 月 11 日
編集済み: Guillaume 2019 年 7 月 11 日
one way:
C1 = [1 1 1 1 1 2 2 2 2 2 2 3 3 3 4 4 4 4] %this is valid matlab syntax
C2 = [5 10 12 35 3 1 4 26 5 11 12 8 2 22 8 2 5 7] %We can just copy/paste that into matlab
transitions = find(diff([-Inf, C1, Inf]) ~= 0);
result = [C1(transitions(1:end-1)); C2(transitions(2:end)-1) - C2(transitions(1:end-1))].'
edit: Note that this assumes that your grouping indices (C1) are not mixed (It wouldn't work with C1 = [1 1 1 2 2 1 1 2] for example)

その他の回答 (1 件)

Matt J
Matt J 2019 年 7 月 11 日
編集済み: Matt J 2019 年 7 月 11 日
[~,i]=unique([C1,C1(end+1)],'stable');
result = C2(i(2:end)-1)-C2(i(1:end-1))

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by