Export results from several excel files into one excel file

6 次查看(过去 30 天)
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?

回答(1 个)

Raghava S N
Raghava S N 2025-4-8,8:33
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);
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')
Hope this helps!

标签

Community Treasure Hunt

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

Start Hunting!

Translated by