Anyone an idea? Variable in nested for loop does not update...

2 views (last 30 days)
Dear Community,
I made the following script to automatize my data analysis:
clear, clc
myDir = uigetdir; %gets directory
myFiles = dir(fullfile(myDir,'*_DistX.xlsx'));
for k = 1:length(myFiles)
baseFileName = myFiles(k).name;
fname = strcat(myFiles(k).name);
fullFileName = fullfile(myDir, baseFileName);
fprintf(1, 'Now reading %s\n', baseFileName);
opts = detectImportOptions(fname ,'NumHeaderLines',0);
T = readtable(fname, opts)
A = table2array(T)
NumberOfParticles = length(A(:,1))
for i = 1:NumberOfParticles
NumberOfZero(i) = sum(A(i,:)==0);
NumberOfRetrograde(i) = sum(A(i,:)<0);
NumberOfAnterograde(i) = sum(A(i,:)>0);
TotalNumber(i) = numel(rmmissing(A(i,:)));
B = [(NumberOfRetrograde)', (NumberOfZero)', (NumberOfAnterograde)', (TotalNumber)']
C = array2table (B,'VariableNames',{'NumberOfRetrograde', 'NumberOfZero', 'NumberOfAnterograde','TotalNumber'})
D(k,:) = [sum(NumberOfRetrograde), sum(NumberOfZero), sum(NumberOfAnterograde), sum(TotalNumber)]
E = array2table (D, 'RowNames',{fname},'VariableNames',{'NumberOfRetrograde', 'NumberOfZero', 'NumberOfAnterograde','TotalNumber'})
It works fine, except for the variable B, which does not update through iterations of k, which messes up C,D and E consequentially.
Anybody an idea where the problem could be? Is it possible that the first "end" closes both for loops?
Thanks a lot in advance for any idea...

Answers (1)

Uttiya Ghosh
Uttiya Ghosh on 19 Jun 2020
Hi Mara,
I have checked your code assuming the data in your file as a table of size 3*3 containing integers. I am also assuming that you want to store the data for each file as a row in variable D. Since you are using the variable fname as rownames for the variable E, you should consider creating it as a vector of strings and not just a single string. You should also try to compute E outside the outer for loop. I believe these steps will solve your error. I have made the following changes to your code and placed variable E outside the loop which solved the issue.
fname(k) = string(myFiles(k).name);
opts = detectImportOptions(baseFileName ,'NumHeaderLines',0);
T = readtable(baseFileName, opts);
E = array2table (D, 'RowNames',fname,'VariableNames',{'NumberOfRetrograde', 'NumberOfZero', 'NumberOfAnterograde','TotalNumber'});
You can then write the variable E in a file as required.
For more information, refer to the links given below:


Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by