Warning: Variable appears to change size on every loop iteration (within a script). Consider preallocating for speed.
26 views (last 30 days)
Show older comments
Hello. I am working on a project where I've created a while-loop to calculate 3 power values and 4 cost values. I need to run this loop 60 times. I receive the warning shown in the summary and 3x4 double for my cst variable and 4x3 double in my power variable. I'm trying to store the values in a table so I can see all 60 values of P1, P2, P3, F1, F2, F3, and Ft. I'm very new to MATLAB and I cannot figure out how to get past the fact that I can apparently only get to 12 values each for cost and power. Here is my code:
% Group 2 - Part I.b. Optimal Power Flow with Gradient Search
% Start fresh - clear command window, variables, and plots
clc, clearvars, close all
% Initialize the values
P1 = 300;
P2 = 200;
P3 = 850 - P1 - P2;
n = 0;
k = 60;
alpha = 10;
% Initialize the cost functions
F1 = 561 + 7.92 * P1 + 0.00156 * P1^2;
F2 = 310 + 7.85 * P2 + 0.00194 * P2^2;
F3 = 78 + 7.97 * P3 + 0.00482 * P3^2;
Ft = F1 + F2 + F3;
% Initialize the gradient of the cost functions
gradientF1 = (7.92 + 0.003124 * P1 - 7.97 - 0.00964 * P3);
gradientF2 = (7.85 + 0.00388 * P2 - 7.97 -0.00964 * P3);
gradientF3 = [gradientF1;gradientF2];
while n < k
x = [P1;P2];
n = n + 1;
% Update power values
P1 = P1 - alpha * gradientF1;
P2 = P2 - alpha * gradientF2;
P3 = 850 - P1 - P2;
power(n,1) = P1; %#ok<*SAGROW>
power(n,2) = P2;
power(n,3) = P3;
cst(n,1) = F1;
cst(n,2) = F2;
cst(n,3) = F3;
cst(n,4) = Ft;
end
% Initialize arrays
power_array = zeros(3,60);
cst_array = zeros(4,60);
% Store power values
power_array(k, :) = [P1, P2, P3];
% Store cost values
cst_array(k, :) = [cst1, cst2, cst3, cst4];
% Display results
disp('Final Power Values:');
disp(power_array(end, :));
disp('Final Cost Values');
disp(cst(end, :));
% Plot power values
figure;
plot(3:60, power);
title('Power Values');
xlabel('Iterations');
ylabel('Power (MW)');
legend('P1', 'P2', 'P3');
% Plot cost values
figure;
plot(4:60, cst);
title('Cost Values');
xlabel('Iterations');
ylabel('Cost ($/hr)');
legend('F1', 'F2', 'F3', 'F4');
0 Comments
Answers (1)
Walter Roberson
on 21 Apr 2024
power = zeros(k, 3);
cst = zeros(k, 4);
before the while loop.
0 Comments
See Also
Categories
Find more on Refactor Models in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!