Is it possible to report built-in functions and provide alternative for further releases?
5 views (last 30 days)
Show older comments
I've found that a pretty basic built-in function nchoosek is far from ideal, and I have a way to improve it. Is it possible to report it somehow? Here's the code for nchoosek:
function c = nchoosek(v,k)
% the function, not really interesting, only the combs part
end
%----------------------------------------
function c = binCoef(n,k,classOut)
%a helper function, also not important
end
%----------------------------------------
function P = combs(v,m)
%COMBS All possible combinations.
% ...
v = v(:).'; % Make sure v is a row vector.
n = length(v);
if n == m
P = v;
elseif m == 1
P = v.';
else
P = [];
if m < n && m > 1
for k = 1:n-m+1
Q = combs(v(k+1:n),m-1);
P = [P; [v(ones(size(Q,1),1),k) Q]]; %#ok %<--- here's the problem
end
end
end
end
The problem is obviously at the %#ok line. That is not OK and runs really slow. We know the size prior, so preallocating is not a problem. My proposition is the following really simple algorithm for combs(1:n,m)
function [P] = combs(n, m)
%COMBS
vals = 1:m;
total = nchoosek(n, m);
P = zeros(total, m);
for I=1:total
P(I, :) = vals;
for M = m:-1:1
if vals(M)<n-m+M
vals(M) = vals(M)+1;
for MM = (M+1):m
vals(MM) = vals(M) + MM - M;
end
break;
end
end
end
end
Clearly this problem received some exposure by this question but I wonder if there's a way to do this directly.
3 Comments
Accepted Answer
Steven Lord
on 25 Aug 2018
If you believe you've found a bug or have a suggestion for an enhancement request, please contact Technical Support using the Contact Us link in the upper-right corner of this page.
More Answers (0)
See Also
Categories
Find more on Introduction to Installation and Licensing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!