How to create a cell array in a loop that produces other arrays

My code is 3 for loops (or while loops) which ultimately create a cell array A that contains 11 cells each of which is a huge matrix.
My code works perfectly fine except for the fact that cell array A stores the cost array of the last run only! I have 11 runs producing an array cost and I expect the cost of each run to be stored in a distinct cell of the cell array A.
The line code where I face the problem is A{b}=cost
x_grid_max = 1000;
y_dc_max = 550;
y_dc_min = 200;
grid_res = 1;
plant_capacity_fixed = sum(Buildings_Info(4,:));
dc_cost_fixed = mean(1800, 3500)*plant_capacity_fixed;
pipe_thermal_loss=11.2*0.000284345; %11.2W/m
B=11;
b=1;
while (b<=B)
while(y_dc_min<= y_dc_max)
x=1;
while (x<=x_grid_max)
disp(x)= sqrt((Buildings_Info(2,b) - y_dc_min)^2 + (Buildings_Info(1,b) - x)^2);
pipe_cost(x) = disp(x).*mean(2300, 5000);
plant_capacity_variable(x)= disp(x).*pipe_thermal_loss;
dc_cost_variable(x)= mean(1800, 3500).*plant_capacity_variable(x);
dc_cost_total(x) = dc_cost_fixed + sum(dc_cost_variable(x)) + sum(pipe_cost(x)); %#ok<*SAGROW>
x=x+grid_res;
end
cost(y_dc_min,:)=dc_cost_total;
dispt(y_dc_min,:)=disp;
y_dc_min=y_dc_min+grid_res;
end
A{b}=cost;
b=b+1;
end

1 Comment

You have not specified what is the error? I suspect you should initialize A as cell.

Sign in to comment.

 Accepted Answer

In between the lines:
while (b<=B)
while(y_dc_min<= y_dc_max)
you don't reset your y_dc_min variable, so it really pretty much runs through the b = 1 loop and then assigns the same cost matrix to each cell value in A, so it's actually only stores the cost array of the first run. To fix this simply put in:
while (b<=B)
y_dc_min = 200; % may want to make the reset a variable so if you change it down the line it gets changed in both places.
while(y_dc_min<= y_dc_max)
and you'll get different values in each cell entry of A (you'll also notice that the code takes ~ 11 times longer to run.
Just as a side note, it looks like you're using Matlabs mean function incorrectly. How you have it set up it's taking two separate entries (the second entry is dimension). For example with you'll get:
mean(1800, 3500) = 1800
when I think you're looking for:
mean([1800, 3500]) = 2650

More Answers (0)

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Tags

Asked:

on 20 Aug 2017

Commented:

on 22 Aug 2017

Community Treasure Hunt

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

Start Hunting!