MATLAB: File-loop, for loop,importing excel data

fileloopfor loopimporting excel dataxlsreadxlswrite

Hi everyone,
I have the following code, I have problem with the read-in-for-loops.
-I would like to read in several .csv files then export them separetly to excels -even different sheets is okay (it would be great to have the same title/name)
-then I would like to import/read-in these new excel files and work with the 16th column to find local maximas.
I know it's fulll with mistakes, and I am sorry about that, I am really new to MatLab coding I am studying it by myself, so please instead of judging the code, could you help me out?
I would really appraciate any help, thanks in advance, Grace.

Best Answer

%Read each CSV file, change the text data to numeric and work with it
clear;
clc;
dirroot='C:\Documents\Excel\';
for L=1:2
dirname = [dirroot, 'L', num2str(L)];
files = dir([dirname,'*.csv']); % Listing all files in the given
% directory with the extension of csv
filenames = {files.name};
for i=1:size(filenames, 2) % load all the csv files separately
t = readtable(string(filenames{i})); % Give me the csv file in a table
t.Var1 = str2double(string(t.Var1)); % convert the first 2 variables from characters in cells to doubles
t.Var2 = str2double(string(t.Var2)); % text is replaced by NaN (not a number)
data = table2array (t); % convert to double array
[rows, columns] = size(data); % The size of the matrix (the number of
% elements is the same for all columns
% in a matrix, also nr 16)
is_max_rows = islocalmax(data(:,16)) % logical vector of all local max in
% column 16
local_max_col_16 = data(is_max_rows, 16) % value of local maxima in column 16
[rowsWith50, colsWith50] = find(data == 50); % Find out all the rows/cols that have a 50
% in them.
theMax = max(data(:,unique(colsWith50))) % get the max of the columns with a 50
% without repetition of the columns with
% 2x or more 50
save([dirname, 'results_L_', num2str(L), '_dataset_', num2str(i)]); % save data
end
end
It might not be the most elegant way how I did it, either. But it should work if the structure of all the files is the same (text in first 2 columns).
But lmk how you get along!