Export results from several excel files into one excel file
5 views (last 30 days)
Show older comments
Hi,
The plan of my code is this: I want to import several xlsx files. Afterwards I do some calculations. This calculations lead to one line of results for each file. In the end I want to have one file, with one line for every imported file.
I start in my code with a for loop, so that the calculation is made for all excel files (anzahl_files is the number of imported files):
for xy=1:anzahl_files
fid_in=fopen(char(filename(xy)),'r');
Afterwards I import the data and do some calculations (not so interesting for the question):
tmpImport = importdata(filename{xy},',');
SP_RL = tmpImport.Tabelle1;
SP_RL = regexprep(SP_RL,'\''','');
SP_RL = string(SP_RL);
[NumRows NumCols]=size(SP_RL);
Anzahl_Partikel_RL= NumRows;
for m=1:anzahl_elemente
idx = strfind(SP_RL, element_V_RL(:,m));
idx = find(not(cellfun('isempty', idx)));
Elementanzahl_RL(:,m) = length(idx);
end
Now I have with Elementanzahl_RL my final line. Which I want to export now in one file, row after row into a new file. Therefore I tried to have a for loop like this:
for j=1:anzahl_files
Partikel_RL(j+1,:)=Elementanzahl_RL(j,:);
end
end
Anzahl_files is my number of files, which I imported. The second end in this part, is for the first for loop. But sadly its not working and gives me following error:
Index in position 1 exceeds array bounds (must not exceed 1).
Error in TOF_Skript_SingleParticlesgesamt (line 81)
Partikel_RL(j,:)=Elementanzahl_RL(j,:);
I dont find my mistake, does somebody has an idea?
0 Comments
Answers (1)
Raghava S N
on 8 Apr 2025
Before the loop
for xy=1:anzahl_files
.
.
end
You can pre-allocate the matrix "Partikel_RL" with zeros like this:
Partikel_RL = zeros(anzahl_files, anzahl_elemente);
Read more about preallocation here - https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html
Now, after this, you can store the final line result of each excel file in "Partikel_RL" like so:
Partikel_RL(xy,:)=Elementanzahl_RL;
There is no need for a loop, as this operation is vectorized.
for j=1:anzahl_files
Partikel_RL(j+1,:)=Elementanzahl_RL(j,:);
end
end
The above loop can be removed.
After the outer xy loop ends, each final line result of each of the excel files will be a row in the "Partikel_RL" matrix.
This matrix can then be written into a single excel file like this:
writematrix(Partikel_RL,'Results.xlsx')
For more details about writing MATLAB arrays to excel files, refer to this link - https://www.mathworks.com/help/matlab/ref/writematrix.html#:~:text=25%092%099-,Write%20Matrix%20to%20Spreadsheet%20File,-Write%20Matrix%20to
Hope this helps!
0 Comments
See Also
Categories
Find more on Spreadsheets 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!