Anyone an idea? Variable in nested for loop does not update...
1 view (last 30 days)
Show older comments
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,:)));
end
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'})
writetable(E,fname,'Sheet',1,'Range','A1')
end
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...
0 Comments
Answers (1)
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:
0 Comments
See Also
Categories
Find more on Data Type Conversion 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!