Fill table field based on field values from another table

I want to move values from one table to a different table based on matching field names across both tables. I'm hoping to do so without using costly for loops, as the dataset is fairly large. I've tried using ismember and field indexing, but it seems so clunky and I can't get it to work.
In the example below, Tables A and B already exist and both have the field "ID". Table A may have other fields, but new fields are trying to be added. The goal is to fill "NewField1", "NewField2", and "NewField3" in Table A based on the corresponding fields in Table B. In the image below, the yellow cells indicate fields I'd like to be filled.
This is exceptionally straightforward in Excel with VLOOKUP, but I'm having trouble finding an efficient analog in MATLAB.

 Réponse acceptée

I think you can actually join the two tables. I find the live task for joining tables the quickest way to get the correct settings. Having done that, here is the equivalent code.
% Create tables
ID = ["Alabama";"Alaska"];
Field1 = [nan;1];
Field2 = [2;nan];
Field3 = [4;8];
A = table(sortrows([ID;ID;ID]),'VariableNames',"ID");
B = table(ID,Field1,Field2,Field3);
% Join tables
joinedData = join(A,B,"Keys","ID")
joinedData = 6×4 table
ID Field1 Field2 Field3 _________ ______ ______ ______ "Alabama" NaN 2 4 "Alabama" NaN 2 4 "Alabama" NaN 2 4 "Alaska" 1 NaN 8 "Alaska" 1 NaN 8 "Alaska" 1 NaN 8

Plus de réponses (0)

Catégories

Produits

Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by