0

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?

1 Answer 1

0

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'}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.