Loop on changing databases
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Hi,
We run a code where part of it depends on variables we import from excel.
We want to run a loop on the code for it to run 20 times importing the variable from different excel files to create scenarios. Each scenario has to be saved automatically. The name of the variables never change.
Can we do this?
Thank you very much
0 comentarios
Respuestas (1)
Abhiram Bhanuprakash
el 6 de Jul. de 2015
Hi Alexandra,
Yes you can do this using xlsread to read from different Excel files. The structure of the code would look like this:
excelFilenamesCellArray = {Array of Excel file names/paths as strings};
for i=1:20
[num,txt,raw] = xlsread(excelFilenamesCellArray{i});
%Create scenario
%Save as separate file using (may be) xlswrite?
xlswrite(filename,<scenario_variable>);
end
I'm not sure what you mean by 'scenario', so the above code is not complete. You can modify it as per your requirement.
Doc for xlsread and xlswrite are at:
Hope this helps,
Cheers!
Abhiram
3 comentarios
Abhiram Bhanuprakash
el 6 de Jul. de 2015
Hi Alexandra,
The code which I shared was not meant to be the exact code but a sample demonstrating how you can approach this.
For your latest questions, I have the following suggestions:
1. Say if you have two files named 'filename1.xlsx' and 'filename2.xlsx'. You can define:
excelFilenamesCellArray = {'filename1.xlsx', 'filename2.xlsx'};
2. If you need an increasing index, you can make it depend on the loop counter variable and make the filename, sheet and xlRange cell arrays.
For example, you can do something like:
for cnt=1:20
%Earlier code
filename{cnt} = ['XX', num2str(cnt), '.xlsx'];
sheet{cnt} = ['sheet', num2str(cnt)];
xlRange{cnt} = ['xlRange', num2str(cnt)];
end
3. If you want to do this using 20 rows in a unique excel file, you can use xlsread only only outside the for loop. If you check the doc for xlsread, you can see that, if you use this kind of syntax:
[num,txt,raw] = xlsread(___)
You will get the raw data (both text and numbers) from the Excelsheet. You can use index on this raw data to extract rows/columns of your choice.
Hope this helps,
Cheers!
Abhiram
Ver también
Categorías
Más información sobre Spreadsheets en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!