-4

我想改变第 n 个向量的条件以覆盖一系列 i 值(类似于 i=2:27)。

N=51;
num =2; 
W = 3;
i = 2;

string1 = '[';
for n = num:-1:1
    string1 = [ string1 'a' num2str(n) ' '];
end
string1 = [ string1 '] = ndgrid(1:W);'];

string2 = 'ind = find(';
for n = 2:num
    string2 = [ string2 'a' num2str(n) '>=a' num2str(n-1) '&' ];
end

for n = 1:num
    string2 = [ string2 'a' num2str(n) '+'];
end
string2 = [ string2(1:end-1) '==i);' ];

string3 = 'C = [ ';
for n = 1:num
    string3 = [ string3 'a' num2str(n) '(ind) ' ];
end
string3 = [ string3 ']' ];
eval(string1);
eval(string2);
eval(string3);

不幸的是,我很难理解这是对我最初构造的概括。

最终,我需要在概率分析中使用矩阵 p2(它选择 a1、a2 到 an 的组合)。

4

1 回答 1

0

以下是您的操作方法:

N = 5; % number of columns, this was your a1 ... a5

W=3; % unchanged to first example in question
i=6; % unchanged to first example in question

% the following will create a matrix with N-1 columns
% because the last column is determined by the sum of the columns before it
% the a1 .. an-1 columns contains all possible permutations of 1:W
% (this code can be found on the internet)

for ii=1:N-1
    dset{1,ii}=1:W;
end

n=numel(dset);
a=cell(n,1);
[a{1:n}]=ndgrid(dset{end:-1:1});
a=reshape(cat(n+1,a{:}),[],n);
a=a(:,end:-1:1);

% next, we sort the rows ascending 
% because for you, 1-1-2 is the same as 1-2-1
% and after sorting, we pick the unique rows

a = unique(sort(a,2),'rows');

% next, we populate the last column
% and select those that match your criterion
% in a matrix p2n

p2n = [];

for ii=1:size(a,1)
    a(ii,N) = i - sum(a(ii,1:N-1));
    if(a(ii,N-1) <= a(ii,N) && a(ii,N)<=W)
        p2n=[p2n;a(ii,:)];
    end
end

请参阅代码中的注释以获取解释。

编辑
如果您想改变N,iW,请使用for-loops 例如:

for N=2:4
    for i=2:27
        for W=3:7

        % post code starting at line 11 here
        % DO NOT DECLARE N, W, i inside the loops again

        % Also, introduce a cell to store all `p2n` matrices: 
        % place this inside the loop but below the code given above

        P2n{N,i,W} = p2n; 

        end
    end
end
于 2013-08-09T16:54:58.917 回答