Search code examples
matlabfor-loopdatatablesexport-to-csv

Extracting table within a for loop


I'm attempting to run a for loop and within this loop I'm attempting to extract a table, within every iteration of the loop itself.

Currently I am able to write to a table, which if I step through the code allows me to manually go and save the created table, before running through and it gets overwritten again. All I need is, to be able to extract the table and rename it before it gets overwritten in the next iteration of the loop.

I currently have the follwoing code:

clc 
clear all

%% Parameters

data = readtable('Input/Wales_Interim_23/Pembrokeshire_23_Finished.csv');

data.Unit = extractBefore( data.Reg_ID, '_' ); %Extract the unit number prior to the 
transect line.
gidx = findgroups( data.Unit ); %Identify the individual unit groups. 

N = max(gidx);         % gidx is [1,2,...,N] for N unique IDs.
units = cell(N,1);     % pre-allocate an output cell.

% Loop over the IDs and assign the subsets of data.
for ii = 1:N 
    units{ii} = data( gidx==ii, : );
    writetable(units{ii});
end


%Find the outputted tables in 'Units'.

The code essentially runs through a CSV file, identifies unique groups within the list and then assigns these groups to a cell array. I'm uncertain as to where I need to place a 'write table' function within the loop and how to get the script to export a table for each unique group.


Solution

  • Managed to sort the issue by defining a 'unit_name' at the start of the loop and then using this name within the output of the 'writetable' function.

    for ii = 1:N 
        unit_name = string(ii);
        units{ii} = data( gidx==ii, : );
        writetable(units{ii}, unit_name);
    end