Octave中实现按指定数量筛选数组组合的自定义函数方法
Hey there! Let’s work through this Octave problem together. From what you’ve described, you want a custom function that lets you pick exactly n elements from array b (with the rest coming from a), and you need it to work with arrays of any dimension—not just 1D. You’ve already generated all possible combinations, so let’s focus on the filtering step first, then also cover a more efficient approach that avoids generating every single combination upfront (which can get slow for larger arrays).
First: Filtering Pre-Generated Combinations
If you already have all possible combinations stored (say, in a multi-dimensional array where each slice is one combination), here’s how to filter for those that use exactly n elements from b:
Step-by-Step Logic
- Align dimensions: Make sure your
all_combinationsarray has the same base dimensions asa/b, with an extra dimension holding all the combinations. - Count matches with b: For each combination, count how many elements are taken from
b. - Filter valid combinations: Keep only the combinations where the count equals
n.
Code Example
% Example setup: a and b are 1D arrays, all_combinations is your pre-generated array a = [1,2,3]; b = [4,5,6]; all_combinations = % Your pre-generated combinations array here (e.g., 3x8 for 2^3 combinations) % Calculate how many elements from b are in each combination % Repmat b to match the size of all_combinations, then compare and sum b_expanded = repmat(b, [1, size(all_combinations, 2)]); % Adjust repmat args based on your array dimensions counts = sum(all_combinations == b_expanded, 'all'); % Get indices of combinations with exactly n elements from b valid_indices = find(counts == n); % Extract the valid combinations filtered_combinations = all_combinations(:, valid_indices); % Adjust indices for multi-dimensional arrays
Note: For multi-dimensional a/b (like 2D or 3D), adjust the repmat arguments to match the dimensions of all_combinations. The sum(..., 'all') function counts all matching elements across the entire combination slice.
More Efficient Approach: Generate Only Valid Combinations
Generating every possible combination first is inefficient (especially for larger arrays—2^L combinations gets huge fast). Instead, we can directly generate only the combinations that use exactly n elements from b. Here’s a custom function that works for any array dimension:
Custom Function Code
function filtered_combinations = select_n_from_b(a, b, n) % Check if a and b have the same dimensions if ~isequal(size(a), size(b)) error("Error: a and b must have identical dimensions!"); end % Flatten arrays to 1D for easy handling (works for any input dimension) a_flat = a(:); b_flat = b(:); total_elements = length(a_flat); % Validate n is within a valid range if n < 0 || n > total_elements error("Error: n must be between 0 and %d (total elements in a/b)", total_elements); end % Generate all sets of positions where we'll use elements from b b_positions = nchoosek(1:total_elements, n); num_valid = size(b_positions, 1); % Initialize result array: same base dimensions as a/b, plus an extra dimension for combinations result_dims = [size(a), num_valid]; filtered_combinations = zeros(result_dims); % Build each valid combination for i = 1:num_valid % Start with a's elements, replace n positions with b's elements current_comb = a_flat; current_comb(b_positions(i, :)) = b_flat(b_positions(i, :)); % Reshape back to original dimensions and store filtered_combinations(:, :, i) = reshape(current_comb, size(a)); % Adjust indices for 3D+ arrays end end
How to Use This Function
% 1D example a = [1,2,3]; b = [4,5,6]; n = 2; result = select_n_from_b(a, b, n); % Result will be a 3x3 array where each column is a valid combination: % [4;5;3], [4;2;6], [1;5;6] % 2D example a = [1 2; 3 4]; b = [5 6; 7 8]; n = 2; result_2d = select_n_from_b(a, b, n); % Result will be a 2x2x6 array, with each 2x2 slice being a valid combination with exactly 2 elements from b
Key Features
- Works with any dimension: Flattening the input arrays lets us handle 1D, 2D, 3D, or even higher-dimensional arrays seamlessly.
- Efficient: Uses
nchoosekto generate only the positions we need, avoiding the overhead of creating all possible combinations. - Input validation: Checks for matching dimensions and valid
nvalues to prevent errors.
内容的提问来源于stack exchange,提问作者jorpilo

