Compare files with MATLAB

后端 未结 5 1516
时光取名叫无心
时光取名叫无心 2021-01-22 06:36

I would like to know how could I compare two files (line by line) (*.xml, .m,.txt,...etc) using MATLAB.

file1 = \'toto.xml\';
file2 = \'titi.xml\';
         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-22 07:18

    First you can read both files by lines:

    fid1 = fopen(file1, 'r');
    fid2 = fopen(file2, 'r');
    
    lines1 = textscan(fid1,'%s','delimiter','\n');
    lines2 = textscan(fid2,'%s','delimiter','\n');
    lines1 = lines1{1};
    lines2 = lines2{1};
    
    
    fclose(fid1);
    fclose(fid2);
    

    You will have 2 cell arrays lines1 and lines2. You can compare the whole arrays with

    tf = isequal(lines1,lines2);
    

    Comparing lines is not so obvious and depends on your need. What you want to do if number of lines is different? For example, to find which lines from file2 exist in file1 (independently of order) you can do:

    [idx1 idx2] = ismember(lines1,lines2);
    idx2(idx2==0) = [];
    

    idx1 will be logical index representing lines in file1 that have the same lines in file2. idx2 will be numeric (position) index of where those lines located in file2 (the first occurrence).

    If the number of lines are the same:

    idx_same_lines = strcmp(lines1,lines2);
    

提交回复
热议问题