sum of different columns to the desired value in Matlab
1 view (last 30 days)
Show older comments
I have list of numbers from Row 1 to Row 20 say in Column A and I need to have the number of each row distributed in to four different columns (Column B, C, D, E) in Matlab so that:
(i) the sum of values shown in columns B, C, D, E is equal to the value of Column A.
(ii) The values shall only be whole numbers.
(iii) Columns B, C, D, E have maximum limit of 10, 10, 5 and 5 respectively. That is the values generated in these columns should be with in these maximum limit values.
Example:
| A | B | C | D |
| 16 | 6 | 5 | 2 | 3 |
Any way to pick values from Column A and then get the values in different columns (B,C,D,E) with in their respective limits so that the sum is equal to A?
Sample Column A values are as under:
16
17
20
26
18
29
19
20
18
16
16
21
16
16
17
16
28
29
20
25
16
Previously for another similar project I tried doing this with limits of 3 and 5. But here I need to get values from A and then do the summation within limits.
clear all
while true
A=randi([3 5],20,4);
if((sum(A,2)>=42) | (sum(A,2)<=70));
break;
end
end
disp(A);
disp(sum(A,2));
2 Comments
Mohammad Sami
on 5 Aug 2022
If the column is not given but is generated. You can just generate the values for BCDE and then sum it up to get the value for A
Accepted Answer
Bruno Luong
on 5 Aug 2022
Edited: Bruno Luong
on 5 Aug 2022
A=randi([4 30],10,1);
lo = [1 1 1 1];
up = [10 10 5 5];
BCDE=lo+diff(round((cumsum([0, (up-lo)],2)).*(A-sum(lo))./sum(up-lo)),1,2); % EDIT bug fix
if any(BCDE < lo | BCDE > up)
error('Fail')
end
[A,BCDE]
2 Comments
Bruno Luong
on 5 Aug 2022
Edited: Bruno Luong
on 5 Aug 2022
Hmm just change it at your will
A=randi([16 30],10,1);
lo = [5 5 3 3];
up = [10 10 5 5];
BCDE=lo+diff(round((cumsum([0, (up-lo)],2)).*(A-sum(lo))./sum(up-lo)),1,2); % EDIT bug fix
if any(BCDE < lo | BCDE > up)
error('Fail')
end
[A,BCDE]
More Answers (1)
Bruno Luong
on 5 Aug 2022
If you have the optimization toolbox
A=randi([4 30],10,1);
n = length(A);
lo = [1 1 1 1];
up = [10 10 5 5];
m = length(up);
BCDE = zeros(n,m);
opts = optimoptions('intlinprog','Display','off');
for k=1:n
BCDE(k,:) = intlinprog(zeros(1,m),1:m,...
[],[],ones(1,m),A(k),lo,up,[],opts);
end
[A(:) BCDE]
4 Comments
See Also
Categories
Find more on Dates and Time 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!