问题
Hi I have the 3 dimensional matrix in the code below. I am trying to sum all the 24 elements of "n" for every "number_panels" and "number_turbines" combination.
what I have below doesn't sum across the 3rd dimension
for number_panels = 0:5
for number_turbines = 0:2
for n = 1:24 % number of hours per day
hourly_deficit(number_panels + 1, number_turbines + 1, n) = Demand(n) -...
(PV_supply(n)*number_panels) - (WT_supply(n)*number_turbines);
if hourly_deficit(number_panels + 1, number_turbines + 1, n)< 0
hourly_deficit(number_panels + 1, number_turbines + 1, n) = 0;
end
daily_deficit(number_panels + 1, number_turbines + 1) = sum(sum(sum(hourly_deficit(:,:,:))))
hourly_total_RES(number_panels + 1, number_turbines + 1, n) = PV_supply(n)*number_panels + WT_supply(n)*number_turbines;
if hourly_total_RES(number_panels + 1, number_turbines + 1, n) < Demand(n),
renewables_penetration(number_panels + 1, number_turbines + 1, n) = (hourly_total_RES(number_panels + 1, number_turbines + 1, n)) / Demand(n); % ratio of renewable energy supply to demand
else
renewables_penetration(number_panels + 1, number_turbines + 1, n) = 1 ;
end
peak_deficit(number_panels + 1, number_turbines + 1,n) = max(hourly_deficit(number_panels + 1, number_turbines + 1,n));
end
回答1:
In MATLAB sum(X) adds all elements of matrix X in one dimension. If you want to just calculate the sum for one specific dimension use:
S1=sum(X,dimension);
where "dimension" is 1, or 2, or 3 for a 3D matrix.
If you want to compute over two dimensions then you can do:
S2=sum(S1,dimension);
where dimension here is 1, or 2.
Based on your code I think this is what you should do if you want to do it in for loops:
for number_panels = 0:5
for number_turbines = 0:2
for n = 1:24 % number of hours per day
hourly_deficit(number_panels + 1, number_turbines + 1, n) =...
Demand(n) - (PV_supply(n)*number_panels) - (WT_supply(n)*number_turbines);
if hourly_deficit(number_panels + 1, number_turbines + 1, n)< 0
hourly_deficit(number_panels + 1, number_turbines + 1, n) = 0;
end
daily_deficit(number_panels + 1, number_turbines + 1) = ...
sum(hourly_deficit(number_panels + 1, number_turbines + 1,:));
end
end
Look at the ":" that I added to: sum(hourly_deficit(number_panels + 1, number_turbines + 1,:));
来源:https://stackoverflow.com/questions/11484039/sum-3dimensional-matrix-matlab-brute-force