How can I read in comma separated data from csv where some cells contain multiple numeric values that are also comma separated?

35 views (last 30 days)
Hi
I have a csv file that I'd like to import into Matlab. It contains a range of Numeric and String data. The function 'readtable' works fine for the most part. The problem I'm having is that the final column you can see below (MouseX) contains comma separated numbers, that when using the readtable function just produces one long number.
To be clear, I don't care about MouseX being in the same table as the rest of the data. I just want a numeric array for MouseX where each current value in a cell has it's own cell. So based on what you can see here, there are 6 cells containing data in MouseX, and each contains 7 comma separated values. So I'd want a 6 x 7 numeric array. It's also worth noting though, that there are a variable number of values in each of those cells.
I've tried reading that colum in separately, using different delimiters, changing from Number to Text etc. The latter kind of worked, in that it produced a string array where the numbers were still comma separated as they appear in the table below. But then I could only think of a clunky loop to extract each value and put it in a numeric array. It took forever to run.
I'm sure there's a more efficient way. I think textscan might be the answer, but I couldn't quite figure it out. There are so many input options! Any help would be much appreciated.
Thanks
Ricci

Accepted Answer

ANKUR KUMAR
ANKUR KUMAR on 19 Mar 2021
Edited: ANKUR KUMAR on 19 Mar 2021
"there are 6 cells containing data in MouseX, and each contains 7 comma separated values. So I'd want a 6 x 7 numeric array.": Ths query has the solution, becuse you can have a matrix of 6X7. But your next statement, "It's also worth noting though, that there are a variable number of values in each of those cells.", if number of values are different in different cells, creating a matrix is not possible unless you are adding summy values in the rows.
csv = readtable("myStopData_MousePos_test_2.csv")
array=csv.MouseX;
array_cell=array(cellfun(@(x) ~isempty(x),array))
array_cell=cellfun(@(x) str2double(strsplit(x,',')),array_cell,'uni',0)
If all cell have the same array size, you can have that in a matrix
cat(1,array_cell{:})
  1 Comment
Ricci Hannah
Ricci Hannah on 19 Mar 2021
Thanks! I found a function someone else had posted to concatenate vectors of different lengths with NaNs (https://www.mathworks.com/matlabcentral/fileexchange/22909-padcat) and it all seems to work together nicely. Really appreciate the help! Seems I really should get my head around cellfun instead of using inefficient loops.

Sign in to comment.

More Answers (0)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!