Creating new matrices with input depending on csv filename

2 views (last 30 days)
I have a bunch of csv files containing charge and discharge data that I would like to separate into a charge matrix and a discharge matrix.
The filenames in the folder for the charge data are CYCLE0_CHG, CYCLE2_CHG, CYCLE4_CHG, etc. and the filenames for the discharge data are CYCLE1_DIS, CYCLE3_DIS, CYCLE5_DIS, etc.
The following is my initial step at dividing the files into 2 variables based on their file name.
filepath = 'C:\Kikusui testing\12s2p Cycling\CH1_2023_3_6_14_32';
fileinfo1 = filepath(dir('_CHG.csv'));
fileinfo2 = filepath(dir('_DIS.csv'));
However, I am getting the error "Unable to use a value of type struct as an index."

Accepted Answer

Stephen23 on 22 Mar 2023
Edited: Stephen23 on 22 Mar 2023
If you want those file names to be sorted into alphanumeric order then you will either need to generate the filenames (e.g. SPRINTF or similar) or sort the output from DIR:
P = 'C:\Kikusui testing\12s2p Cycling\CH1_2023_3_6_14_32';
C = dir(fullfile(P,'CYCLE*_CHG.csv'));
D = dir(fullfile(P,'CYCLE*_DIS.csv'));
C = natsortfiles(C); % download:
D = natsortfiles(D); % download:
for k = 1:numel(C)
F = fullfile(P,C(k).name);
C(k).data = readmatrix(F); % or READTABLE, etc.
for k = 1:numel(D)
F = fullfile(P,D(k).name);
D(k).data = readmatrix(F); % or READTABLE, etc.
Optional, assuming compatible arrays sizes and classes:
Cdata = vertcat(; % charge
Ddata = vertcat(; % discharge
Stephen23 on 22 Mar 2023
"Could you please clarify what this line means F = @(m) m(:,16:25); % all rows from columns 16 to 25."
F is the handle to an anonymous function. The anonymous function takes one input argument m (a matrix) and returns all rows for columns 16 to 25 of the input matrix.
"Is @m just an anonymus function and if so, why do I use that?"
@m does not exist in my code.
I specified the anonymous function so that I could use CELLFUN to process all cells of Ccell and Dcell. As an alternative you could always use a FOR loop.
"I used the code above and received the following error: Index in position 2 exceeds array bounds. Index must not exceed 1."
Then one (or more) of your matrices has only one column, not 25 columns. MATLAB will throw an error if you ask it for the content of the 25th column from a matrix with only one column.

Sign in to comment.

More Answers (0)





Community Treasure Hunt

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

Start Hunting!

Translated by