MATLAB: For loop output each iteration to cell array

cell arraysfor loop outputs

I have some code below, the problem I'm having is that I want to output each iteration into the cell array P_SUM, and not just the final one. I'm not sure if I understand how for loops work, but I'm hoping it runs through the whole code in order (from the first for to the last end) before starting over. The way I'm currently doing it is by copying the whole code 40 times and changing the value of 'y', which I'm sure is not the most efficient way to do it. xs_current is a cell array containing 40 arrays of different sizes, I've attached it to this post aswell.
EDIT: It might be abit unclear on what the code is supposed to do; so I'll try to explain it in a simpler way. The first 'for' is supposed to choose what array of xs_current to use The second 'for' uses a function to compute the outputs of the function for all values of the array chosen previously The third 'for' sums all the outputs produced previously and outputs them into an array. Finally, the array produced in the third 'for' is supposed to be stored in a cell array, with the position defined by the first 'for'.

Best Answer

It appears that you need to move the preallocation of P_SUM to before the main loop:
P_SUM = cell(1,numel(xs_current));
for y = 1:numel(xs_current) %(read 'for y = 1:40')
xs_n = xs_current{y}; %Selects which array in xs_current to use.
P_n = cell(1,numel(xs_n)); %Pre allocate new cell array to contain arrays computed by function comp_press...
for x_n = 1:numel(xs_n) %How many iterations to run next loop for
P_n{x_n} = comp_press_field_point_source(1500,1,(-0.002:5e-05:0.002),(0:5e-05:0.004),0,xs_n(x_n),0,0,(0:1e-08:4e-06)); %runs function for x_n number of iterations, changing the input of xs_n for each iteration, outputs to cell array P_n
end
P_SUM_n = 0; %set initial value of P_SUM_n
for sum_n = 1:numel(P_n) %How many iterations to run for loop for
P_SUM_n = P_SUM_n + P_n{sum_n}; %Sums all arrays within P_n
end
P_SUM{y} = P_SUM_n; %store output from loop into cell array, P_SUM, in position corresponding to loop number.
end
Your code alingment was rather uneven, which makes understanding the code much harder, so I fixed that as well.