嘿大家我用octave搞砸了一点我遇到了一个问题,有:
a = [1,2,3] b = [4,5,6]
我想创建一个函数,以便:
n选择b元素的数量
n = 0
result = a1*a2*a3 --> 1*2*3
----
n=1
result = b1*a2*a3+a1*b2*a3+a1*a2*b3 --> 4*2*3+1*5*3+1*2*6
----
n=2
result = b1*b2*a3+b1*a2*b3+a1*b2*b3 --> 4*5*3+4*2*6+1*5*6
----
n=3
result = b1*b2*b3 --> 4*5*6
它必须支持其他尺寸而不是3
我怎么能这样做?
编辑1
到目前为止,我能够使用以下方式生成所有可能的对:
var1 = [1,4]
var2 = [2,5]
var3 = [3,6]
[x y z] = ndgrid(var1,var2,var3);
cartProd = [x(:) y(:) z(:)];
这会产生我:
cartProd =
1 2 3
4 2 3
1 5 3
4 5 3
1 2 6
4 2 6
1 5 6
4 5 6
这是所有可能的组合,我的问题是如何能够通过他们在每个数组中使用的组合数来过滤它们
答案 0 :(得分:0)
我终于修复了自己,我使用了一些简单的矩阵运算来实现它:
%I make a vector with all 0 of the size of a or b
multiply_vect = zeros(size(a));
% 0 0 0
%I change to 1 n elements of the vectors (the elements I want from B)
n = 2
multiply_vect(1:n) = 1;
% 1 1 0
%I make all posible unique permutations with the elements of the vector
multiply_matrix = unique(perms(multiply_vect), 'rows');
% 1 1 0
% 0 1 1
% 1 0 1
%In order to get the bs that I want I multiply each component of my multiply_matrix with b
b_matrix = multiply_matrix .* b
% 4 5 0
% 0 5 6
% 4 0 6
%I do the same with a but multiply it with the complementary of the matrix
a_matrix = ((1-multiply_matrix) .* a)
% 0 0 3
% 1 0 0
% 0 2 0
%I just have to add both matrix component by component
sum_matrix = b_matrix .+ a_matrix
% 4 5 3
% 1 5 6
% 4 2 6
%the only thing left is doing the product of each row and sum all of them
result = sum(prod(sum_matrix'))
% 60
% 120
% 48
% result = 60+120+48 = 228
% code together all together:
a = [1,2,3];
b = [4,5,6];
n = 2;
multiply_vect = zeros(size(a));
multiply_vect(1:n) = 1;
multiply_matrix = unique(perms(multiply_vect), 'rows');
result = sum(prod(((multiply_matrix .* b) .+ ((1-multiply_matrix) .* a))'));