How to import several csv files (Nan,numeric,text) for operate with them after

4 views (last 30 days)
I want to import several csv files in matlab (each one for one streamflow station) where I have seasonal flows.This the structure of the each csv is the following:
I am trying to do in several ways but without success:
This the first way I tried:
% Get an array of all files
basepath = 'C:\Users\salonsov\Desktop\Results_lowflows\seasons';
files = dir(fullfile(basepath, '*.csv'));
% Pre-allocate data storage
data = cell(size(files));
% Import each file using it's filename
for k = 1:numel(files)
data{k} = csvimport(fullfile(basepath, files(k).name));
end
My I go the error that Unrecognized function or variable 'csvimport'.
I have also tried using csvread instead of csvimport, but I have an error because my data has NaN values.
I have tried also with read.table, but I cannot save the files in a cell.
After importing the csv files, I want to loop over them to perform some operations.
What is it the best way to import csv files and after operate with them in matlab?
  16 Comments

Sign in to comment.

Accepted Answer

Jeremy Hughes
Jeremy Hughes on 6 Apr 2021
I suggest readtable.

More Answers (1)

Stephen23
Stephen23 on 8 Apr 2021
"I want the cells to be rename because I want to know to which station corresponds the data in each cell. As you can see I could import the data, but now I am not sure how to know at which station corresponds each cell data."
A simpler, neater, more efficient solution is to use the structure returned by DIR:
P = 'C:\Users\salonsov\Desktop\Results_lowflows\seasons';
S = dir(fullfile(P, '*.csv'));
for k = 1:numel(S)
F = fullfile(P, S(k).name);
S(k).data = csvimport(F); % or READTABLE or whatever.
end
Take a look in the structure S: it contains all of your file data and the corresponding filenames, just as you require.
For example, the 2nd filename and its data:
S(2).name
S(2).data
Accessing and processing this will be much simpler than messing around with dynamically named variables.

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!