Subtract column values where leading columns have values flipped (i.e., (A,B,C1) - (B,A,C2))
78 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Image Analyst
le 23 Juin 2024 à 14:49
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:
Réponses (1)
dpb
le 23 Juin 2024 à 16:35
Modifié(e) : dpb
le 24 Juin 2024 à 15:56
load answers T
T
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
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.
0 commentaires
Voir également
Catégories
En savoir plus sur Annotations dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!