Compare values from two text files and replace if they match
7 次查看(过去 30 天)
显示 更早的评论
I have a problem of comparing two text files and replace value in third column if values in two first column match.
I have to text files. Each with tree columns (with the same format).
Text file 1 (short example):
177.50 0.00 1
180.00 0.00 1
0.00 10.00 1
2.50 10.00 1
5.00 10.00 1
7.50 10.00 1
10.00 10.00 1
12.50 10.00 1
Txt file 2 (short example):
2.50 10.00 0.01177
2.50 20.00 0.00977
5.00 0.00 -0.01480
5.00 10.00 -0.01244
5.00 20.00 -0.00440
5.00 30.00 -0.00228
I want to compare values of the first and second column in Text file 1 with the values in first and second column in Text file 2. If both values matches I want to replace “1” in third column in Text file 1 by corresponding value from third column from Txt file 2. The final output will be modified Text file 1 where in third column will be “1” in rows “not present” in Txt file 2 and values from Txt file 2 – in rows which match to Txt file 2.
For presented example output Text file 1 should look like this:
177.50 0.00 1
180.00 0.00 1
0.00 10.00 1
2.50 10.00 0.01177 %“1” was replaced by 0.01177 because this value is in Text file 2 in row “2.50 10.00”
5.00 10.00 -0.01244 %“1” was replaced by -0.01244 because this value is in Text file 2 in row “5.00 10.00”
7.50 10.00 1
10.00 10.00 1
12.50 10.00 1
Would be great if someone could help me out! Thanks in advance!
采纳的回答
Guillaume
2019-7-9
Assuming you've imported your two text files as matrices:
%m1, m2: matrices corresponding to each text file:
[ismatch, whichrow] = ismember(m1(:, [1 2]), m2(:, [1 2]), 'rows'); %find which rows match and where the match is in m3
m1(ismatch, 3) = m2(whichrow(ismatch), 3); %replace column 3 of m1 by column 3 of m2 for match
Note that if there are duplicate matches in m2, the first one will be used.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String Parsing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!