Reading specific from user selected csv file

2 visualizaciones (últimos 30 días)
Anthony Urciuoli
Anthony Urciuoli el 11 de Mzo. de 2021
Comentada: Walter Roberson el 12 de Mzo. de 2021
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!

Respuestas (1)

Walter Roberson
Walter Roberson el 11 de Mzo. de 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 comentarios
Walter Roberson
Walter Roberson el 12 de Mzo. de 2021
error('Failed to open file "%s" because: "%s"', filename, msg);
Walter Roberson
Walter Roberson el 12 de Mzo. de 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

Iniciar sesión para comentar.

Categorías

Más información sobre Environment and Settings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by