How to use "csvread" when the contents in a file have different formats?

I have. CSV file, and the format is shown below:

mapping.csv

5188.40811,TMobileML 5131.40903,TMobileGregsapt 5119.40791,TMobileJonsapartment 5123.40762,TMobileRedhat 

I want to store it in a 4 by 2 array, when I have a value, such as 5131.40903 (this is a "string" not an "int"), I want to find the display relation, which is TMobileGregsapt , But I meet two problems, firstly, I can't use csvread('mapping.csv') , it will have some error: (I think the problem may be 5131.40903 will be int when I use csvread, but TMobileGregsapt is a line ...)

 ??? Error using ==> dlmread at 145 Mismatch between file and format string. Trouble reading number from file (row 1, field 2) ==> TMobi Error in ==> csvread at 52 m=dlmread(filename, ',', r, c); 

although I use dlmread('cell4.csv', ',') , it still has some error:

 ??? Error using ==> dlmread at 145 Mismatch between file and format string. Trouble reading number from file (row 1, field 2) ==> TMobi 

The second problem is how easy it is to find the mapping relation, the naive method uses forloop to find the position of the array.

Thank you for your help:)

+3
source share
2 answers

Both csvread and dlmread only work for numeric data. Something like this should work for you

 out=textread('tmp.csv', '%s', 'whitespace',','); nums = out(1:2:end); strs = out(2:2:end); % find index of 'TMobileGregsapt' ind = find(strcmp('TMobileGregsapt',strs)); nums(ind) 
+7
source

Another answer that will work if you have mixed text / csv number, but you either don’t know which format or it is heterogeneous, use the csv2cell function from: http://www.mathworks.com/matlabcentral/fileexchange/20836 -csv2cell

 c = csv2cell( 'yourFile.csv', 'fromfile'); 

c(1, :) will provide your headers, and c(2:end, k) will provide you with each of the columns (without a header), for k = 1:size(c, 2)

+2
source

Source: https://habr.com/ru/post/1482254/


All Articles