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 Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by