Working with tables: populate column of NaNs in table 1, with contents of column of table 2, given a condition.

1 vue (au cours des 30 derniers jours)
I have some data in testing.mat (uploaded to this thread), two tables with two common columns: 'letter' and 'vals'.
On t_1, my 'vals' column is full of NaNs, I'd like to fill it with the values of the 'vals' column of t_2. I managed to achieve this with a for loop and using strcmp.
My question for the forum is, is it possible to do this in a single line or two? Without "for" loops? I have not tried it yet, but outerjoin could help me, the thing is I think the command will leave the two 'vals' column if I do the merge using that key.
What do you recommend?

Réponse acceptée

Jacob Wood
Jacob Wood le 19 Fév 2020
It is possible to do with a small amount of code. The easiest way to utilize a table like your "t_2", where the "letter" column contains unique values, is to label the rows. After labelling the rows you can use logical indexing to access the values you are looking to replace:
t_2.Properties.RowNames = t_2.letter; %Label rows
nan_idx = isnan(t_1.vals); %Find letters that need to be looked up
t_1.vals(nan_idx) = t_2(t_1.letter(nan_idx),:).vals; %Label these with values from t_2

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by