フィルターのクリア

Subtract column values where leading columns have values flipped (i.e., (A,B,C1) - (B,A,C2))

78 ビュー (過去 30 日間)
Neel Kulkarni
Neel Kulkarni 2024 年 6 月 23 日 13:19
編集済み: dpb 2024 年 6 月 24 日 15:56
Suppose I have a table, T:
A B C
1 6 10
2 5 20
3 4 30
4 3 45
5 2 6
6 1 10
I want to subtract each entry in column C where the A and B values are flipped, and put this value into column D
For example, the first row (1, 6, 10) - the last row (6, 1, 10); (2, 5, 20) - (5, 2, 6) and so on
So D should be:
0
14
-15
15
-14
0
Thanks a lot!
Edit: (i) Flipped rows could occur anywhere in the table; (ii) there may be repeated values in Α and B
  10 件のコメント
Image Analyst
Image Analyst 2024 年 6 月 23 日 14:49
Do you have a table variable, or a double variable? Can you attach your variable in a mat file?
save('answers.mat', 'T');
When you say "flipped" do you mean vertically or horizontally? Your original example seemed to have it both ways. Now it seems just that you mean horizontally, so that columnA is in columnB and ColumnB is in columnA, so in essence for a particular row, colA and colB are swapped.
If you have any more questions, then attach your data and code to read it in with the paperclip icon after you read this:
Neel Kulkarni
Neel Kulkarni 2024 年 6 月 23 日 15:20
@Image Analyst Hi, it is a table variable. I have attached the mat file with my example above. It indeed is a horizontal flip.

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

回答 (1 件)

dpb
dpb 2024 年 6 月 23 日 16:35
編集済み: dpb 2024 年 6 月 24 日 15:56
load answers T
T
T = 8x3 table
A B C _ _ __ 1 6 4 2 6 9 2 5 10 3 6 10 4 3 45 5 2 13 6 2 6 6 1 10
T.D=nan(height(T),1);
for i=1:height(T)
ix=find(all(fliplr(T{:,1:2})==T{i,1:2},2));
try
T.D(i)=T.C(i)-T.C(ix);
catch
end
end
T
T = 8x4 table
A B C D _ _ __ ___ 1 6 4 -6 2 6 9 3 2 5 10 -3 3 6 10 NaN 4 3 45 NaN 5 2 13 3 6 2 6 -3 6 1 10 6
The above is the "dead ahead" solution that computes the difference for every record in the file; one could be a little more clever and set both i and ix (to the negative difference) in the one loop iteration. Then one would need to make and update the list of records yet to be handled to know when to quit. The list would start initialized to 1:height(T) and each i, ix would be removed each iteration. When empty, quit.
The above does nothing when there is no match, thereby leaving the initial default NaN value; your choice as to what to do here if this isn't the desired result. Your initial example had no unpaired records and your followup didn't define what is the desired result for those records. In this case, the catch clause would have to remove those i entries. Whether shortening the number of iterations would "win" over the extra logic probably would depend upon how large T is.

カテゴリ

Help Center および File ExchangeAnnotations についてさらに検索

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by