Reputation: 247
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
Those % notes
are for helping me express the problem I want to solve in my mind, and later on, in my script.
Lets claim that we want for each i
to store values in a matrix of costs of the drinks and food it orders.
So for people 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]) !!!
for people 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]) !!!
for people 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 want to form every result of each i
th iteration to a Matrix in ascending order
Matrix(i) = sort (j [x,y]).
Perhaps not the best paradigm, but thank you in advance.
Upvotes: 0
Views: 203
Reputation: 7028
(Two ways I understood your statement; I'm presuming you're interested in 2. solution. In this form Resultx
and Resulty
don't depend on i
in any way, and therefore they'll be the same for all the "people").
1. Matrix
is [ k x 2 ] array. Results from second loop are summed up!
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
Last command sorts pairs, first by 1st column, then by 2nd column in ascending order. If you would like descending order for both criteria, you would use [-1 -2]
instead. Combining ascending and descending is also possible (for example [-1 2]
) but senselessness is questionable in this case.
2. Matrix
is [ k x l x 2 ] array in which the results are kept individually and are not summed up in second loop.
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
Note: You should do avoid writing loops in Matlab and resort to vectorized solution wherever possible!
Upvotes: 2