MATLAB: Extract data with a loop cycle from structure

loop csv structures

Hi,
I need to extract data from structure iteratively as multiple tables.
The response with this code is: 'Unable to use a value of type cell as an index.'
Furthemore I'd like to plot the extracted data.
Many thanks,
Code:
directory = '/Users/Dati/';
S = dir(fullfile(directory,'*.csv'));
for k = 1:numel(S)
F = fullfile(directory,S(k).name);
S(k).data = readtable(F, 'PreserveVariableNames', true, 'ReadVariableNames', true);
end
for i = 1: numel(S)
out(i) = S({i}).data;
end

Best Answer

The correct syntax is
directory = '/Users/Dati/';
S = dir(fullfile(directory,'*.csv'));
for k = 1:numel(S)
F = fullfile(directory,S(k).name);
S(k).data = readtable(F, 'PreserveVariableNames', true, 'ReadVariableNames', true);
end
out = cell(1, numel(S))
for i = 1: numel(S)
out{i} = S(i).data;
end
You need to store the tables in a cell array.
Also, second for-loop is not needed. Following is equivalent
directory = '/Users/Dati/';
S = dir(fullfile(directory,'*.csv'));
for k = 1:numel(S)
F = fullfile(directory,S(k).name);
S(k).data = readtable(F, 'PreserveVariableNames', true, 'ReadVariableNames', true);
end
out = {S.data};
Related Question