0
for i=1:1:k   %k = 100 people
   for j=1:1:l  %l = 5 orders
      Resultx = a + b + d(j); % cost of drink Resultx
      Resulty = f + g + c(j); % cost of food Resulty
   end
   Matrix(i) = [Resultsx1...j Resulty1...j]
end

这些% notes是为了帮助我表达我想在脑海中解决的问题,然后在我的脚本中。

让我们声称我们希望每个i人都将值存储在它订购的饮料和食物的成本矩阵中。

所以对于人来说i = 1

1[1 5] %people 1, first order:  drink costs 1 and food costs 5
2[2 3] %people 1, second order: drink costs 2 and food costs 3
      ...
j[x y] %people 1, j order:      drink and food costs x and y
                 !!!       Matrix(1) = sort (j [x,y])    !!!

为人i = 2

1[1 5] %people 2, first order:  drink costs 1 and food costs 5
2[2 3] %people 2, second order: drink costs 2 and food costs 3
     ...
j[x y] %people 2, j order:      drink and food costs x and y
       !!!       Matrix(2) = sort (j [x,y])    !!!

为人i = k

1[1 5] %people k, first order:  drink costs 1 and food costs 5
2[2 3] %people k, second order: drink costs 2 and food costs 3
      ...
j[x y] %people k, j order:      drink and food costs x and y
            !!!       Matrix(i) = sort (j [x,y])    !!!

我想按升序将每次迭代i每个结果形成一个矩阵

Matrix(i) = sort (j [x,y]).

也许不是最好的范例,但提前谢谢你。

4

1 回答 1

2

(我理解您的陈述的两种方式;我假设您对2.解决方案感兴趣。以这种形式Resultx并且Resultyi以任何方式依赖,因此它们对于所有“人”都是相同的)。

1. Matrix[k x 2]数组。总结了第二个循环的结果!

Matrix = zeros(k, 2);                 % pre-allocate space

for i=1:1:k   %k = 100 people
    Resultx = 0;
    Resulty = 0;        
    for j=1:1:l  %l = 5 orders
        Resultx = Resultx + a + b + d(j);       % cost of drink Resultx
        Resulty = Resulty + f + g + c(j);       % cost of food Resulty
    end
    Matrix(i,:) = [Resultx, Resulty]  % save pair
end

Sorted = sortrows(Matrix, [1 2]);     % sort pairs

最后一个命令对 pair 进行排序,首先按第一列,然后按升序按第二列。如果您希望这两个条件都按降序[-1 -2]排列,则可以改用。结合升序和降序也是可能的(例如[-1 2]),但在这种情况下,无意义是值得怀疑的。

2. Matrix[ k x l x 2 ]数组,其中的结果单独保存,不会在第二个循环中汇总。

Matrix = zeros(k, l, 2);              % pre-allocate space
Intermediate = zeros(l, 2);           % container used for sorting

for i=1:1:k   %k = 100 people
    for j=1:1:l  %l = 5 orders
        Resultx = a + b + d(j);       % cost of drink Resultx
        Resulty = f + g + c(j);       % cost of food Resulty
        Intermediate(j,:) = [Resultx, Resulty];  %save pair
    end
    Matrix(i,:,:) = sortrows(Intermediate, [1 2]);  % sort pairs
end

注意: 您应该避免在 Matlab 中编写循环,并尽可能使用矢量化解决方案!

于 2012-11-13T08:42:29.860 回答