使用Optimization Toolbox时如何解决数组索引必须为正整数或逻辑值错误
Let's walk through exactly why your code is throwing that error and how to fix it, plus clean up a few other issues to get your cut-set boundary curve working correctly.
1. Why the Index Error Happens
The line r(M) = -ropt is the culprit. You're using M (a floating-point number like 0, 0.1, 0.2...) as an index for the array r. MATLAB requires array indices to be positive integers (1, 2, 3...) or logical values—decimals and 0 are invalid here.
2. Step-by-Step Fixes
Here's how to adjust your code to resolve this and other minor issues:
a. Pre-Initialize the Results Array Correctly
Instead of redefining r inside the loop (which wipes previous results), create an array that matches the length of your M sequence upfront:
N = 60; t = 3; K = 130; M_values = 0:0.1:1.4; % Store M sequence in a variable r = zeros(size(M_values)); % Initialize r to match the length of M_values
b. Use Integer Indices for Assignments
Loop over the index of M_values instead of the values themselves, so you have a valid integer index for r:
for idx = 1:length(M_values) M = M_values(idx); % Get the current M value % Rest of your loop code here... r(idx) = -ropt; % Use integer index idx to store results end
c. Fix the Logical Condition
Your original condition if f || c is backwards. You want to run the optimization only when 1/K ≤ M ≤ t*N/K (approx 0.0077 ≤ M ≤ 1.3846). So use logical AND (&&) instead of OR (||):
lower_bound = 1/K; upper_bound = t*N/K; f = M >= lower_bound; c = M <= upper_bound; if f && c % Run optimization here end
d. Clean Up the Objective Function Initialization
Your original r=zeros(size(1:M)); was invalid for M < 1 (since 1:M would be an empty array). We already fixed this by pre-initializing r outside the loop.
3. Full Corrected Code
N = 60; t = 3; K = 130; M_values = 0:0.1:1.4; r = zeros(size(M_values)); % Pre-allocate results array lower_bound = 1/K; upper_bound = t*N/K; for idx = 1:length(M_values) M = M_values(idx); % Check if M is within the valid range is_valid = (M >= lower_bound) && (M <= upper_bound); if is_valid % Define the objective function (note: fmincon minimizes, so we keep the negative) R2 = @(s) -(s - (s./floor(N./s)).*M); LB = 1; UB = min(N, K); options = optimoptions('fmincon','Algorithm','interior-point'); % Run optimization [sopt, ropt] = fmincon(R2, 1, [], [], [], [], LB, UB, [], options); r(idx) = -ropt; % Store the positive delivery rate else r(idx) = NaN; % Mark invalid M values as NaN (won't plot) end end % Plot the results plot(M_values, r, 'r-', 'LineWidth', 2); xlabel('Cache Capacity (M)'); ylabel('Delivery Rate (R)'); grid on; % Optional: add grid for readability
4. What This Fixes
- The index error is resolved by using integer indices (
idx) for therarray. - Valid M values are correctly filtered with the logical AND condition.
- Results are preserved across loop iterations because
ris pre-allocated outside the loop. - Invalid M values are marked as
NaN, so they won't show up in your plot (keeping only the valid cut-set boundary curve).
内容的提问来源于stack exchange,提问作者Fatma Ahmed

