# Can you parameterize table lookup, i.e. t1.A(i) = t2.A(t2.B==t1.B(i)), so it does not require a loop?

조회 수: 2(최근 30일)
Ulf Molich 2022년 8월 2일
댓글: Ulf Molich 2022년 8월 2일
I know this question must have been asked somewhere before, but I have failed to find it answered.
I have two tables, that looks something like this:
ID = {1;2;3};
Name = {'Joe';'Alex';'Lily'};
t1 = table(ID,Name);
ID = {1;1;3;1;2;3;1;3;2};
t2 = table(ID);
n = height(t2);
Now, I want to enrich t2 with names, by looking up which ID corresponds to which name in t1. What is the most efficient way to do this? In my experience, doing it in a loop like this is painfully slow:
t2 = addvars(t2,cell(n,1),'NewVariableNames', {'Name'});
for i = 1:n
t2.Name(i) = t1.Name(t1.ID == t2.ID(i));
end
I found this thread on using cellfun instead of a loop, but it seems that for that specific case, a loop is faster.

댓글을 달려면 로그인하십시오.

### 채택된 답변

Stephen23 2022년 8월 2일
편집: Stephen23 2022년 8월 2일
If you stored the IDs as basic numeric arrays, rather than inefficiently as complex cell arrays containing lots of numeric scalars, then this would be simple and efficient using one of the JOIN() family:
ID = [1;2;3];
Name = {'Joe';'Alex';'Lily'};
t1 = table(ID,Name)
t1 = 3×2 table
ID Name __ ________ 1 {'Joe' } 2 {'Alex'} 3 {'Lily'}
ID = [1;1;3;1;2;3;1;3;2];
t2 = table(ID)
t2 = 9×1 table
ID __ 1 1 3 1 2 3 1 3 2
t2 = join(t2,t1)
t2 = 9×2 table
ID Name __ ________ 1 {'Joe' } 1 {'Joe' } 3 {'Lily'} 1 {'Joe' } 2 {'Alex'} 3 {'Lily'} 1 {'Joe' } 3 {'Lily'} 2 {'Alex'}
##### 댓글 수: 1표시숨기기 없음
Ulf Molich 2022년 8월 2일
This is perfect! I knew there was a simple answer. Thank you very much.

댓글을 달려면 로그인하십시오.

R2021a

### Community Treasure Hunt

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

Start Hunting!