Search code examples
matlabcsvcell-array

How to identify a cell as a string or number or both before writing out to csv in Matlab


I want to write out multiple cell arrays to csvs in Matlab within a loop. The cell arrays contain both strings and numbers. My problem is that some of them contain both strings AND numbers sometimes: For example: Elevation can be recorded as '200' or '200 metres'...which means that I can't specify either a %f or a %s, because in some instances, it will be wrong and write out incorrectly. Here's what I'm using:

 fid = fopen('test.csv', 'w') ;
fprintf(fid, '%s,\t', csvdata{1,1:end}) ;
fprintf(fid,'\n,%f, %f, %f,%f, %f, %s,%s, %f, %f,%s, %f, %s,%s, %f, %s,%s, %s, %s,%s, %s,%s,%s,%s',csvdata{2,:});
fclose all

Is there a character that can be used to recognise both strings and numbers? Or is there another way to make the code more flexible, to recogise when the data is not a number as expected?


Solution

  • You can craft your format string by checking the datatypes. In the example below, I take the first row of the output and check whether each element is a character (ischar) or not. This yields 0 for non-chars and 1 for chars. I then add 1 to that non-chars become 1 and chars become 2. I then use that to index into a cell array containing the format specifiers. Finally, I join the format string together with commas using strjoin.

    % Get a 1 for numeric data and 2 for character data
    inds = cellfun(@ischar, csvdata(2,:)) + 1;
    
    % Create an array of format specifiers to index into
    formats = {'%f', '"%s"'};
    
    % Index into this array of format specifiers (also append a newline like you've shown)
    formatparts = {'\n', formats{inds}};
    
    % Join everything together with commas
    formatstr = strjoin(formatparts, ',');
    
    % Go ahead and write out the data
    fprintf(fid, formatstr, csvdata{2,:});