我需要将这个嵌套for循环的3个变量转换为n个变量

时间:2017-01-12 12:17:05

标签: matlab

这是我在Pesos时使用变量Nobj=3的程序。在这里,我使用3个嵌套for循环来计算Pesos,但是如何更改代码以便它可以处理Nobj=n

Nobj=3;
Card=10;
delta1=1/(Card-1);
alpha1=0:delta1:1;
    k=0;
    Pesos=zeros(Card^Nobj,Nobj);
    for i=1:size(alpha1,2)
        for ii=1:size(alpha1,2)
            for iii=1:size(alpha1,2)
                k=k+1;
                Pesos(k,:)=[alpha1(i) alpha1(ii) alpha1(iii)];
                if sum(Pesos(k,:))>0
                    Pesos(k,:)=Pesos(k,:)/sum(Pesos(k,:));
                else
                    Pesos(k,:)=[0 0 1];
                end
            end
        end
    end

1 个答案:

答案 0 :(得分:3)

使用ndgrid

对其进行矢量化
% Parameters
N    = 3;
Card = 10;

% Generate regularly-spaced gridded data of identical 
% ranges along N dimensions
alpha1 = linspace(0, 1, Card);       
[Pesos{1:N}] = ndgrid(alpha1);

% Expand and concatenate horizontally
Pesos = cellfun(@(x)x(:), Pesos(N:-1:1), 'UniformOutput', false);    
Pesos = [Pesos{:}];

% Divide by the row sums
Pesos = bsxfun(@rdivide, Pesos, sum(Pesos,2));

% or 
%
% Pesos = Pesos ./ sum(Pesos,2);
%
% if you're on R2016b or later.