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

3 次查看(过去 30 天)
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?

采纳的回答

Jacob Wood
Jacob Wood 2020-2-19
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by