Matlab并将单个结果排序到矩阵

时间:2012-11-12 21:24:01

标签: matlab 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
   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 th 迭代的每个结果形成一个矩阵

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

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

1 个答案:

答案 0 :(得分:2)

(我理解你的陈述的两种方式;我认为你对 2。解决方案感兴趣。在这种形式ResultxResulty don' t以任何方式依赖于i,因此对于所有“人”来说它们都是相同的。)

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

上一个命令sorts pairs,首先是第一列,然后是升序顺序中的第二列。如果您希望两个条件的降序顺序,则可以使用[-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中编写循环并尽可能使用矢量化解决方案!