sum of different columns to the desired value in Matlab
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Mohammad Sami
2022-8-5
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
采纳的回答
Bruno Luong
2022-8-5
编辑:Bruno Luong
2022-8-5
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 个评论
Bruno Luong
2022-8-5
编辑:Bruno Luong
2022-8-5
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]
更多回答(1 个)
Bruno Luong
2022-8-5
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calendar 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!