matlabcsvcell-array

How to convert 1d array of chars from CSV to 2d cell array in Matlab


I have a function I cannot change in Matlab that converts CSV file to a 1d array of chars.

This is an example of what it looks like: array_o_chars = ['1' 'd' ',' ' ' 'a' 'r' 'r' 'a' 'y' '\n' 'o' 'f' ',' ' ' 'c' 'h' 'a' 'r' 's'];

I need to convert it to a 2d "Cell" array for the rest of my code, how do I do it?


Solution

  • The answer is surprisingly simple:

    First, you want to break the char array into the "rows" of the CSV file. Depending on your line ending, you will choose one of these as a delimiter: \n, \r, or a combination of the two. For this example, we are using \n.

    rows = split(array_o_chars, '\n');

    Now that you have your rows, you need to create your columns, this is done in the same manner as your rows, except using , as your delimiter, or in this case , (a comma followed by a space).

    cell_array = split(rows, ', ');

    Now you have the 2d cell array you desire.

    All together now:

    % Test 1d array
    array_o_chars = ['1' 'd' ',' ' ' 'a' 'r' 'r' 'a' 'y' '\n' 'o' 'f' ',' ' ' 'c' 'h' 'a' 'r' 's'];
    
    % Conversion to cell array
    rows = split(array_o_chars, '\n');
    cell_array = split(rows, ', ');
    
    % Show result in Command Window
    display(cell_array);
    

    Output from Matlab:

    cell_array =
    
      2×2 cell array
    
        {'1d'}    {'array'}
        {'of'}    {'chars'}