필터 지우기
필터 지우기

Could anyone help me to get the sum of an array to a fixed value

조회 수: 2 (최근 30일)
jaah navi
jaah navi 2018년 10월 23일
편집: Bruno Luong 2018년 10월 23일
A=[1 2 3 4;
5 6 7 8]
how to get the sum of A to be fixed to a
value of 20 such that all the values in A needs
to be changed according to it.
  댓글 수: 3
madhan ravi
madhan ravi 2018년 10월 23일
Give an example of your desired output
jaah navi
jaah navi 2018년 10월 23일
There is no fixed logic A=[1 2 3 4; 4 3 2 1] When I sum the above A it gives 20 the value in A needs to be changed such that the sum of A needs to be 20. the values in A can be negative,or it can be repeated more than once,twice,thrice and so on.

댓글을 달려면 로그인하십시오.

답변 (3개)

KSSV
KSSV 2018년 10월 23일
A=[1 2 3 4;
5 6 7 8] ;
A = A(:) ;
iwant = cell([],1) ;
count = 0 ;
for i = 1:length(A)
B = nchoosek(A,i) ;
thesum = sum(B,2) ;
idx = thesum==20 ;
if any(idx)
count = count+1 ;
iwant{count} = B(idx,:) ;
end
end
iwant
  댓글 수: 1
jaah navi
jaah navi 2018년 10월 23일
What i actually need is the sum of A should be 20 and the values in A needs to be changed according to it,but when i run the above code it gives 36.could you please help me on this.

댓글을 달려면 로그인하십시오.


Bruno Luong
Bruno Luong 2018년 10월 23일
"There is no fixed logic"
OK that's easy then
A(:) = 0;
A(1) = 20;
  댓글 수: 3
jaah navi
jaah navi 2018년 10월 23일
if i use the above command i am getting value only in the first place and the rest of the place is 0. But i need to have values in places where A already has values, provided no fixed logic is that the values of A can be changed .
Kevin Chng
Kevin Chng 2018년 10월 23일
편집: Kevin Chng 2018년 10월 23일
How about
A(:)=1;
A(1) = 20-sum(A(2:end));
provided number of element in A lesser than 20.

댓글을 달려면 로그인하십시오.


Bruno Luong
Bruno Luong 2018년 10월 23일
편집: Bruno Luong 2018년 10월 23일
Let's be more serious you can do many thing like shifting
A = A - sum(A) + 20/size(A,1);
or scaling
A = 20 * A ./ sum(A);
or both

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by