MATLAB Answers

How to save each iteration of a nested for loop into a matrix

42 views (last 30 days)
Basically, what I've done is create a script that pulls all the .edf files from a pre-defined folder, extracts their data (record, which is a matrix of EEG voltages which each row of values corresponding to an EEG sensor), and then places each record matrix into another array 'recordlist'. What I'm working on now is running an analysis on each row of 'record' (so for example, finding the max value of each row) and saving that into another matrix 'result'. My problem is that the nested for loop works independently, but when I try to run the whole script only the last column of 'result' displays, and all previous columns are just zeroes.
PS. using the max function is just a placeholder, I know there is a way to calculate the max of each row!!
cd '/Users/xxx/Documents/Research/LRP/eeg_testfiles/'; %define folder
ename = dir('*.edf'); %find all the files within folder that end with .edf
for ii = 1:length(ename) %i = however many files satisfy '*.edf'
array{ii} = (ename(ii).name); %create array that holds all
%.edf files
[hdr, record] = edfread(ename(ii).name);
%Returns the header information
%and a matrix (record) where each row is the data for that variable
recordlist{ii} = record; %place 'record' of each EEG in array recordlist
result = zeros(size(record,1), ii); %prepare matrix to store results
for jj = 1:size(record,1)
X = recordlist{1,ii}(jj,:); % define row jj of the matrix being analyzed
M = max(X); %perform function on row jj
result(jj,ii) = M; %save M into jjth row, iith column of result
end
end
Thank you in advance!

  0 Comments

Sign in to comment.

Accepted Answer

Mohith Kulkarni
Mohith Kulkarni on 7 Dec 2020
Edited: Mohith Kulkarni on 7 Dec 2020
You are trying to create a result matrix which stores the max value of each row in each record. In what you are trying to do the result matrix is being recreated again with zeros for every edfread. You can create result cell array for each record instead of a matrix. This way a new cell array element is created for each new file being read and the previous entries are not lost. Refer to the code below:
result{ii} = zeros(size(record,1)); % Instead of result = zeros(size(record,1), ii);
You can then use this specific entry for current edfread in the nested loop. refer to the code below:
result{ii}(jj) = max(X); % In the nested loop, to store the max for each row instead of result(jj,ii) = M;.

  0 Comments

Sign in to comment.

More Answers (0)

Tags

Products

Community Treasure Hunt

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

Start Hunting!