Compare values from two text files and replace if they match

조회 수: 3 (최근 30일)
UWM
UWM 2019년 7월 9일
댓글: UWM 2019년 7월 10일
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
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 CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by