Azzera filtri
Azzera filtri

Read non-negative cells from a cell array

1 visualizzazione (ultimi 30 giorni)
Damith
Damith il 7 Nov 2014
Risposto: Voss il 9 Gen 2024
Hi,
I have following code to read two csv files. I need to read the non-negative cell values from col 6 of Dt cell array and corresponding cell array from col 5 with YYYY-MM-DD format and store it in "Data" cell array.
Any suggestions to do that inside the for loop. Please see the two csv files attached.
Thanks in advance.
clear all
cd ('<path1>')
myFolder = '<path2>';
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
filePattern = fullfile(myFolder, '*.csv');
csvFiles = dir(filePattern);
celsplt = @(x) strsplit(x, ',' ,'CollapseDelimiters',1);
for k = 1:length(csvFiles)
fid(k) = fopen(fullfile(myFolder,csvFiles(k).name));
out{k} = textscan(fid(k),'%s%s%f','delimiter','\t');
Ds = cellfun(celsplt,out{1,k}{1,1}, 'Uni',0);
Dt{k} = vertcat(Ds{:});
fclose(fid(k));
end
Sample of Dt cell array is shown below.
Dt=
'KH' '100401' 'PH' 'M' '1970-12-31T07:00:00+07:00' '-9999.00' 'mm' 'O'
'KH' '100401' 'PH' 'M' '1971-01-01T07:00:00+07:00' '0.00' 'mm' 'O'
'KH' '100401' 'PH' 'M' '1971-01-02T07:00:00+07:00' '0.00' 'mm' 'O'

Risposte (1)

Voss
Voss il 9 Gen 2024
myFolder = '.';
filePattern = fullfile(myFolder, '*.csv');
csvFiles = dir(filePattern);
N = numel(csvFiles);
Data = cell(N,1);
for k = 1:N
C = readcell(fullfile(myFolder,csvFiles(k).name));
Data{k} = C([C{:,6}]>=0,[5 6]); % use 5 instead of [5 6] if you just want the dates
end
disp(Data)
{5113×2 cell} {8681×2 cell}
That makes Data a cell array with a cell for each file. If you want everything together you can do:
Data = vertcat(Data{:})
Data = 13794×2 cell array
{'1971-01-01T07:00:00+07:00'} {[0]} {'1971-01-02T07:00:00+07:00'} {[0]} {'1971-01-03T07:00:00+07:00'} {[0]} {'1971-01-04T07:00:00+07:00'} {[0]} {'1971-01-05T07:00:00+07:00'} {[0]} {'1971-01-06T07:00:00+07:00'} {[0]} {'1971-01-07T07:00:00+07:00'} {[0]} {'1971-01-08T07:00:00+07:00'} {[0]} {'1971-01-09T07:00:00+07:00'} {[0]} {'1971-01-10T07:00:00+07:00'} {[0]} {'1971-01-11T07:00:00+07:00'} {[0]} {'1971-01-12T07:00:00+07:00'} {[0]} {'1971-01-13T07:00:00+07:00'} {[0]} {'1971-01-14T07:00:00+07:00'} {[0]} {'1971-01-15T07:00:00+07:00'} {[0]} {'1971-01-16T07:00:00+07:00'} {[0]}

Categorie

Scopri di più su Cell Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by