Reading specific from user selected csv file

조회 수: 2 (최근 30일)
Anthony Urciuoli
Anthony Urciuoli 2021년 3월 11일
댓글: Walter Roberson 2021년 3월 12일
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일
error('Failed to open file "%s" because: "%s"', filename, msg);
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