Reading CSV file using function

조회 수: 40 (최근 30일)
Sivateja Maturu
Sivateja Maturu 2019년 1월 28일
답변: Siddharth Bhutiya 2019년 1월 31일
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
Sivateja Maturu
Sivateja Maturu 2019년 1월 28일
The original file is attached. I am trying to read data from this csv file and create a 3D Look up table for 2 sets of turbines.
Sarah Crimi
Sarah Crimi 2019년 1월 28일
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.

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

답변 (1개)

Siddharth Bhutiya
Siddharth Bhutiya 2019년 1월 31일
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.

카테고리

Help CenterFile Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by