Adding rows up to a certain value (cell arrays)

1 visualización (últimos 30 días)
Eli Dim
Eli Dim el 30 de Jun. de 2015
Respondida: Star Strider el 30 de Jun. de 2015
I have a cell (curCell_res) which has two columns (column 1 is name and column 2 is the value). I need 230 from column2. This means I need to take everything from A1 to B5 (220) + 10 from C1.
'A1' 27.5
'A2' 16.5
'A3' 22
'A4' 22
'A5' 22
'B1' 27.5
'B2' 16.5
'B3' 22
'B4' 22
'B5' 22
'C1' 27.5
'C2' 16.5
'C3' 22
'C4' 22
'C5' 22
'D1' 27.5
'D2' 16.5
'D3' 22
'D4' 22
'D5' 22
I need to get to an answer cell that looks like this:
'A1' 27.5
'A2' 16.5
'A3' 22
'A4' 22
'A5' 22
'B1' 27.5
'B2' 16.5
'B3' 22
'B4' 22
'B5' 22
'C1' 10
I started writing the code:
DEMAND = 230;
for i = 1:size(BIG,1) %this is the BIG cell array from which curCell_res comes
curCell_res = BIG{i};
for k=1:size(curCell_res,1)
if k==1
Sum_Power(k) = curCell_res(k,2);
elseif k > 1
Sum_Power(k) = curCell_res(k,2) + Sum_Power(k-1);
if Sum_Power(k) > DEMAND
surplus = Sum_Power(k) - DEMAND; %surplus is not needed
not_surplus = curCell_res(k,2) - surplus; the needed bit we have to take
I have problems continuing, I don't know how to formulate the part where I store the the sequence of numbers and the names. Furthermore, I keep on getting errors such as "conversion from double to cell is not possible"... Can you tell me how I should proceed?

Respuesta aceptada

Star Strider
Star Strider el 30 de Jun. de 2015
This produces the output you specified:
curCell_res = {'A1' 27.5
'A2' 16.5
'A3' 22
'A4' 22
'A5' 22
'B1' 27.5
'B2' 16.5
'B3' 22
'B4' 22
'B5' 22
'C1' 27.5
'C2' 16.5
'C3' 22
'C4' 22
'C5' 22
'D1' 27.5
'D2' 16.5
'D3' 22
'D4' 22
'D5' 22};
C2 = cell2mat(curCell_res(:,2)); % Convert 2nd Column To Numeric
cs_curCell_res = cumsum(C2); % Cumulative Sum
T = 230; % Threshold
r = find(cs_curCell_res < T, 1, 'last'); % Last Column Less Than Threshold
Output = [curCell_res(1:r, :); [curCell_res(r+1,1) T-cs_curCell_res(r)]]
Output =
'A1' [27.5]
'A2' [16.5]
'A3' [ 22]
'A4' [ 22]
'A5' [ 22]
'B1' [27.5]
'B2' [16.5]
'B3' [ 22]
'B4' [ 22]
'B5' [ 22]
'C1' [ 10]
The last row of ‘Output’ takes the next name in the series, and calculates the desired value for the second column by subtracting the ‘Threshold’ from the last value less than ‘Threshold’.

Más respuestas (0)

Categorías

Más información sobre Numeric Types en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by