如何在matlab中推广公式

时间:2013-08-08 04:55:45

标签: matlab

我想改变第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到a的组合)。

1 个答案:

答案 0 :(得分: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

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

修改
如果您想要改变NiW,请使用for - 循环,例如:

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