Loop on changing databases

조회 수: 3 (최근 30일)
Alexandra
Alexandra 2015년 7월 2일
댓글: Alexandra 2015년 7월 6일
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

답변 (1개)

Abhiram Bhanuprakash
Abhiram Bhanuprakash 2015년 7월 6일
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
Abhiram Bhanuprakash
Abhiram Bhanuprakash 2015년 7월 6일
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
Alexandra
Alexandra 2015년 7월 6일
Hi Abhiram, it helps. Thanks a lot. I did manage the xlsread but it doesn't insert the variables in the workspace, so the next lines of code don't recognize the variables.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by