This function returns a matrix of all possible binary condition vectors for a logical system with (I) inputs.
The number of inputs is limited only by the user's available system memory. The function is highly efficient, written using only three variables in 16 lines of MATLAB code.
While this is longer in terms of lines than similar functions on MATLAB CENTRAL, it is the quickest and most direct function that obtains the solution (and the only function that doesn't depend on other functions to achieve the result).
INPUT: (I) shall be an integer >= 1
OUTPUT: CONDVECTS is a binary matrix of size [2^I,I]
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Thanks for that. As mentioned in the submission, the there are numerous ways to achieve the result including one liners, on MATLAB CENTRAL. However I just checked the speed of my submission versus your suggestion and mine is around 4 times quicker, which is significant when working with large tables (for order 24, around 17 seconds quicker on my laptop).
I guess this is a reminder that not always the shorter the code implies the fastest execution?
from JOS, did not compare speed
Thanks James, I will attend to those comments. Also, in regard to the treatment of the loop index and link warning, this is the case because I accidentally uploaded a very old version of the function. This issue is not present in the current or previous version of the function. This issue will be corrected shortly. Thanks again, Paul.
This uses a triple-nested while-while-for loop, and yet it *is* faster than the commonly used one-liner dec2bin(0:2^n-1)-'0' approach. I would make the following recommendations:
- Include an H1 line (first line is a comment line with short description of function)
- Include some comments in your code to explain inputs and outputs and method used.
- Is "truth table" really the best name to use?
- You have several instances of repeatedly computing the same expression in a loop that does not depend on the loop index. e.g., 2^i, 2^(m-1), and 2^m. Move those outside the loops to speed things up (I got a 2x increase in speed just by doing that).
- I get a link warning about potentially unused variable k.
I will withhold a rating until you have had a chance to address my comments.
Further minor refinement of code.
The submission is updated to correct performance issues accidentally introduced in the previous version, as well as address the comments of James Tursa.
Added screenshot to download page.
The algorithm is now up to 33% faster thanks to the excellent 'Guideline on writing clean and fast code in MATLAB' by Nico Schlömer.
Slightly updated function description.
Inspired by: Guidelines for writing clean and fast code in MATLAB
Inspired: Benchmark Problem 04 - Formal Methods
Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.