Reading specific from user selected csv file

2 次查看(过去 30 天)
Hello,
I am not good at this so bear with me. I have a .csv file where I want data from column 21 from rows 2 to 633. I want the code to prompt the user to select the csv file they want to analyze. I am importing the data with:
[fname, pname] = uigetfile('*.csv');
filename = fullfile(pname, fname);
However, because my csv file contains text I can not use csvread. Because of this I've tried textscan but am unable to extrat the specifc column and rows above.
Can someone help me write how to get the values I want and assign it to the variable "F"?
I hope I gave enough info, thanks in advance!

回答(1 个)

Walter Roberson
Walter Roberson 2021-3-11
colwanted = 21;
wanted_first_row = 2;
wanted_last_row = 633;
format_of_wanted_information = '%f'; %change to %s if appropriate
fmt = [repmat('%s,', 1, colwanted-1), format_of_wanted_information, '%*[^\n]']; %ignore any further columns on line
[fid, msg] = fopen(filename);
if fid < 1
error('Failed to open file "%s' because: "%s"', filename, msg);
end
header_rows_to_skip = wanted_first_row - 1;
wanted_row_count = wanted_last_row - wanted_first_row + 1;
datacell = textscan(fid, fmt, wanted_row_count, 'Headerlines', header_rows_to_skip);
fclose(fid);
F = datacell{1};
  3 个评论
Walter Roberson
Walter Roberson 2021-3-12
[fname, pname] = uigetfile('*.csv');
filename = fullfile(pname, fname);
assert(exist(filename,'file')==2, '%s does not exist.', filename);
colswanted = [18, 21];
wanted_first_row = 2;
wanted_last_row = 633;
format_of_wanted_information = '%f'; %change to %s if appropriate
lastwanted = max(colswanted);
fmt = [repmat({'%*s,'}, 1, lastwanted), {'%*[^\n]}'];
fmt(colswanted) = {format_of_wanted_information};
fmt = strjoin(fmt, '');
[fid, msg] = fopen(filename);
if fid < 1
error('Failed to open file "%s" because "%s"', filename, msg);
end
header_rows_to_skip = wanted_first_row - 1;
wanted_row_count = wanted_last_row - wanted_first_row + 1;
datacell = textscan(fid, fmt, wanted_row_count, 'Headerlines', header_rows_to_skip);
fclose(fid);
F = datacell{2}; %21
G = datacell{1}; %18
plot(F, G);
The message about input arguments was probably caused by my accidentally using %s instead of %*s

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by