Search code examples
matlabloopsassignnames

Use writetable inside loop in matlab


I'm trying to use writetable command inside a loop. Any help?


Solution

  • MonthNames=['JAN'; 'FEB'; 'MAR'; 'APR'; 'MAY'; 'JUN'; 'JUL'; 'AUG'; 'SEP'; 'OCT'; 'NOV'; 'DEC'];
    for sensorIndex = 1:numel(sensor)
        for monthIndex = 1:numel(MonthNames)
            % Get the current sensor
            k = sensor(sensorIndex);
    
            % Get the file(s?) associated with that sensor
            S = dir(fullfile(path, '*', sprintf('sensor%d.xls', k));
    
            % Create an output filename
            filename = sprintf('sensor%d_%s.xls', k, MonthNames(monthIndex));
            
            % do your stuff
            F = fullfile(S(k).folder,S(k).name);
            data = readtable(F);
            writetable(data, filename);
        end
    end
    

    Doing it this way lets you optionally not have ALL months. Lots of ways to code it, but my personal preference is to keep loop variables as indices and grab the current variable inside the loop using that index.