フィルターのクリア

Loop on changing databases

5 ビュー (過去 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 Center および File ExchangeSpreadsheets についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by