Reading specific from user selected csv file
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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!
0 commentaires
Réponses (1)
Walter Roberson
le 11 Mar 2021
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 commentaires
Walter Roberson
le 12 Mar 2021
error('Failed to open file "%s" because: "%s"', filename, msg);
Walter Roberson
le 12 Mar 2021
[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
Voir également
Catégories
En savoir plus sur Environment and Settings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!