how can I generate a code based on specific value selection in a matrix?
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
JacobM
el 13 de Sept. de 2016
Comentada: JacobM
el 14 de Sept. de 2016
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?
1 comentario
Respuesta aceptada
James Tursa
el 13 de Sept. de 2016
Editada: James Tursa
el 13 de Sept. de 2016
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 comentarios
Más respuestas (1)
John D'Errico
el 13 de Sept. de 2016
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
Ver también
Categorías
Más información sobre Matrices and Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!