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에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!