这是我在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
答案 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.