Import CSV file with mixed data types

前端 未结 9 2304
眼角桃花
眼角桃花 2020-11-27 04:13

I\'m working with MATLAB for few days and I\'m having difficulties to import a CSV-file to a matrix.

My problem is that my CSV-file contains almost only Strings and

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 05:08

    Given the sample you posted, this simple code should do the job:

    fid = fopen('file.csv','r');
    C = textscan(fid, repmat('%s',1,10), 'delimiter',';', 'CollectOutput',true);
    C = C{1};
    fclose(fid);
    

    Then you could format the columns according to their type. For example if the first column is all integers, we can format it as such:

    C(:,1) = num2cell( str2double(C(:,1)) )
    

    Similarly, if you wish to convert the 8th column from hex to decimals, you can use HEX2DEC:

    C(:,8) = cellfun(@hex2dec, strrep(C(:,8),'0x',''), 'UniformOutput',false);
    

    The resulting cell array looks as follows:

    C = 
        [  4]    'abc'    'def'    'ghj'    'klm'    ''            ''                []    ''    ''
        [NaN]    ''       ''       ''       ''       'Test'        'text'        [ 255]    ''    ''
        [NaN]    ''       ''       ''       ''       'asdfhsdf'    'dsafdsag'    [3855]    ''    ''
    

提交回复
热议问题