如何在CPLEX中按单元格索引从Excel读取元组并支持动态范围?
Absolutely, you can make this work! The key is to dynamically construct the range string using CPLEX's string concatenation function, since your n value changes per scenario. Here's a step-by-step breakdown of how to implement this:
Step 1: Define or load your variable n
First, ensure n is a known parameter (not a decision variable—SheetRead runs during data initialization, before solving). You can either hardcode it or read it directly from Excel:
int n; // Example: Read n from Excel cell (1,0) (which is A2 in the "Data" sheet) n from SheetRead(sheet, "'Data'!(1,0)");
Step 2: Build the dynamic range string
Use the concat function to assemble your cell index range, inserting the variable n into the string:
string tupleRange = concat("'Data'!(0,0):(0,", n, ")");
This will generate a string like 'Data'!(0,0):(0,5) if n equals 5, exactly matching your desired format.
Step 3: Load your tuple using the dynamic range
Pass the constructed string to SheetRead to pull in your tuple data:
// Define your tuple structure first tuple MyTuple { int id; float value; // Add other elements as needed for your use case } // Declare your tuple array MyTuple T[]; // Load data with the dynamically generated range T from SheetRead(sheet, tupleRange);
Important Notes
- CPLEX uses 0-based indexing for cell coordinates, so
(0,0)directly corresponds to Excel's A1 cell—this aligns perfectly with your initial example. nmust be a parameter (a fixed value known at data input time). Decision variables won't work here becauseSheetReadexecutes before the solve phase begins.- Double-check that
nis a non-negative integer and that your Excel sheet has enough data in the specified range. Out-of-bounds ranges will trigger CPLEX errors.
内容的提问来源于stack exchange,提问作者StabiloHB

