ismember: Find matching entries in table columns (and add entry from matching row)
54 次查看(过去 30 天)
显示 更早的评论
I have a column A with some participant numbers, column B with a complete list of participant numbers and column C with a complete list of their ages. What I want to do is simply add a column D that contains the ages of the participants in A, i.e. to find each participant number from A in column B and to copy the age from the corresponding row (since B has more rows than A, the rows with the same participant numbers will not match - it's not like B just has additional rows added in the end). However, nothing I tried worked so I'm happy about any tip!
age = readtable('Age.csv','TreatAsEmpty',{'NA'});
for row_number = 1:1000
ismember(age(a,1),age(:,2))
%age(a,4) = age(a,3) %wrong because the corresponding age will not be in row a, but I don't know how to do this
end
The error I get is: Error using tabular/ismember (line 37). A and B must contain the same variables.
...and at that point I did not even try to copy and enter the age, I did not even manage to find matching participant numbers. My attempt at copying and entering the age:
age = readtable('Age.csv','TreatAsEmpty',{'NA'});
for row_number = 1:1000
if ismember(age(a,1),age(:,2))
age(a,4) = age(a,3) %wrong because the corresponding age will not be in row a, but I don't know how else to do this
end
end
I also tried using a structure instead of a table but apparently then I cannot access the different columns. I also considered "containts" and "intersect" but these don't seem right.
0 个评论
采纳的回答
Peter Perkins
2021-8-9
This is a one-liner with tables:
>> A = table([1;3;5])
A =
3×1 table
Var1
____
1
3
5
>> B = table([1;2;3;4;5],[11;12;13;14;15])
B =
5×2 table
Var1 Var2
____ ____
1 11
2 12
3 13
4 14
5 15
>> join(A,B,"Key","Var1")
ans =
3×2 table
Var1 Var2
____ ____
1 11
3 13
5 15
更多回答(1 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!