Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

i wanna generate matrix. the way fixed sum of any matrix. at the same time, will use limiting conditions

조회 수: 1 (최근 30일)
a=[4 5 5 5 5 5 5 5 5];
sum of a is '44'
so, i want to create matrices of sum '44'.
At the same time,
1) first element is started '4'
2) next element must be '4' and over
3) finally, all matrices is arrayed by ascending order
if anyone solve this, i will appreciate it

답변 (2개)

Walter Roberson
Walter Roberson 2017년 2월 21일
You can remove the first item from the total since it is fixed value. Your maximum value could be 40 -- the case [4 40] -- and the maximum length could be 10 (since each value must be at least 4).

Roger Stafford
Roger Stafford 2017년 3월 22일
편집: Roger Stafford 2017년 3월 22일
The following will give all possible sets of six integers as a six-column matrix in accordance with your three conditions. Of course you will want to accomplish this for all numbers of integers from 2 to 11. Six is merely the most numerous (you should get 192 sets with six.) The best method would be to use recursion, and this code is meant to give you some ideas about how to accomplish that recursion.
A = zeros(1000,6);
k = 0;
n1 = 4; % I assumed from 1) the first integer is a fixed 4
for n2 = n1:floor((44-n1)/5)
for n3 = n2:floor((44-n1-n2)/4)
for n4 = n3:floor((44-n1-n2-n3)/3)
for n5 = n4:floor((44-n1-n2-n3-n4)/2)
n6 = 44-n1-n2-n3-n4-n5;
k = k+1;
A(k,:) = [n1,n2,n3,n4,n5,n6];
end
end
end
end
A = A(1:k,:);
fprintf(Number of sets with six integers = %3d\n',k)
all(sum(A,2)==44) % Test
Note: If the first integer can vary, just put another for-loop outside:
for n1=4:floor(44/6)
....
end

Community Treasure Hunt

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

Start Hunting!

Translated by