Reading CSV file using function

110 views (last 30 days)
Sivateja Maturu
Sivateja Maturu on 28 Jan 2019
Answered: Siddharth Bhutiya on 31 Jan 2019
I am trying to read a csv file in the following format. Each row defines one type of variable. Hence I want to read line by line to each of the variable types. Which combination of data import commands should be used to create different variables?
2 %num
15401666 %string
31, 40, 3 %num
3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0, 16.5, 17.0, 17.5, 18.0, %num
216.0, 218.0, 220.0, 222.0, 224.0, 226.0, 228.0, 230.0, 232.0, 234.0, 236.0, 238.0, 240.0, 242.0, 244.0, 246.0, 248.0, 250.0, 252.0, 254.0, 256.0, 258.0, 260.0, 262.0, 264.0, 266.0, 268.0, 270.0, 272.0, 274.0, 276.0, 278.0, 280.0, 282.0, 284.0, 286.0, 288.0, 290.0, 292.0, 294.0, %num
7.5, 12.5, 17.5, %cat
  3 Comments
Sarah Crimi
Sarah Crimi on 28 Jan 2019
I would use csv2cell to get the data into a cell structure in MATLAB. After that you will need a for loop to scan the rows of the cell structure and some if statements. Maybe this https://www.mathworks.com/matlabcentral/fileexchange/20836-csv2cell although I think my copy of MATLAB has this as a command.

Sign in to comment.

Answers (1)

Siddharth Bhutiya
Siddharth Bhutiya on 31 Jan 2019
You can read the file line by line into a cell array and then split each line by the comma delimiter. The code would look something like below
% Read the file line by line into a cell array
fid = fopen(filename);
lines = {};
tline = fgetl(fid);
while ischar(tline)
lines{end+1,1} = tline;
tline = fgetl(fid);
end
fclose(fid);
% Function handle to split each row by comma delimiter
func = @(input)strsplit(input, ',');
% Apply this function to each row in the cell array to get the final data
% As each row is of different lenght we set the UniformOutput to false
data = cellfun(func,lines,'UniformOutput',false);
Once you have the imported cell array you can make the necessary modification to it for further use.

Community Treasure Hunt

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

Start Hunting!