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

조회 수: 33 (최근 30일)
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

채택된 답변

ANKUR KUMAR
ANKUR KUMAR 2021년 3월 19일
편집: ANKUR KUMAR 2021년 3월 19일
"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
Ricci Hannah
Ricci Hannah 2021년 3월 19일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by