how can I generate a code based on specific value selection in a matrix?

조회 수: 22 (최근 30일)
JacobM
JacobM 2016년 9월 13일
댓글: JacobM 2016년 9월 14일
I want to make a function that search for a value of y in x, either one element or sum of many elements, and return 1 or 0 to matrix Z, which is the same size as X, based on the elements chosen from X.
Example:
y=7;
x=[10 -1 -2 -3];
solution will be:
1) 10-1-2=7 ==> Z=[1 1 1 0];
2) 10-3=7 ==> Z=[1 0 0 1];
Any hints?

채택된 답변

James Tursa
James Tursa 2016년 9월 13일
편집: James Tursa 2016년 9월 13일
Here is one way as long as x is not too large. This technique will use too much memory if x is too large.
b = dec2bin(0:2^numel(x)-1)=='1'; % Intermediate step of producing all possible patterns
z = b(b*x'==y,:); % Pick off the rows of b that produce the desired sum
The rows of z contain the patterns that produce the desired sum.
  댓글 수: 8
JacobM
JacobM 2016년 9월 14일
Thanks Andrei for your input, definitely it helps me.
JacobM
JacobM 2016년 9월 14일
This is maybe a follow-up question,
if z2 has 2's instead of 1's and I want them to appear in zout matrix, I did it like this:
z1=[1 0 0 1]; z2=[0 0 0 2; 0 0 2 0]; k = ~any(bsxfun(@and,z1,z2),2); zout = bsxfun(@xor,z1,z2(k,:)); % or as Andrei suggested
index=find(z2==2); % to find the index of 2's in z2 for i=1:length(index) j=index(i); zout(j)=zout(j)*2; % changing 1's to 2's in Zout based in position of 2's in z2 end
but did not work because of the size of zout, the index=6 7 while zout is 1*4 matrix, is there any other way?

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

추가 답변 (1개)

John D'Errico
John D'Errico 2016년 9월 13일
There may be millions, or millions or trillions of solutions, or only a few. Your problem is classically called an integer partition .
https://en.wikipedia.org/wiki/Partition_(number_theory)
For example, the number of distinct ways the number 1000 can be written as the sum of elements from the set [1:1000] is 24061467864032622473692149727991. A BIG number.
You can download my partitions tool from the file exchange, which can generate the entire set (where that is feasible given some rational amount of time and memory.) It allows you to specify the elements to be allowed in the sum.
https://www.mathworks.com/matlabcentral/fileexchange/12009-partitions-of-an-integer
  댓글 수: 1
JacobM
JacobM 2016년 9월 13일
interesting topic, I need to look at the theory and understand it.
I appreciate your help Sir.

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

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by