Message Boards Message Boards

0
|
3614 Views
|
3 Replies
|
6 Total Likes
View groups...
Share
Share this post:

Sorting matrix

Posted 10 years ago
Hi all again, yesterday helped me solve a problem by lists, but now I came the next problem, given following matrix {{3,25,17}, {6,27,33}, {4,29,23 }, {5,37,19}, {7,20,35}, {4,19,31}} sort according to the following condition, the second element must always be greater than the third element, in this example we {6,27,33} note that the third element is greater than the second, in this case to do an exchange to be finally {6,33,27} so is {7,20,35} and finally {4,19,31} which should be respectively {7,35,20} and {4,31,19}.

and the list would look like:
{{3,25,17}, {6,33,27}, {4,29,23}, {5,37,19}, {7,35,20}, {4,31,19}}

thanks in advance. Keep in touch
POSTED BY: Luis Ledesma
3 Replies
m /. {a_, b_, c_} :> If[b < c, {a, c, b}, {a, b, c}]
Above is a slightly differently way of doing this. You can use the RuleDelayed to make the replacement an actual function. The advantage about this one is that all variables are local, therefore, if you happend to define "a" , your result won't de disturbed. (You can see the color of variables are different in In[44] and In[45])
POSTED BY: Shenghui Yang
Posted 10 years ago
many thanks Ilian Gachevski for your help, you give me a lesson in the use of Rules, it is very clear.
POSTED BY: Luis Ledesma
In[1]:= m = {{3, 25, 17}, {6, 27, 33}, {4, 29, 23}, {5, 37, 19}, {7, 20, 35}, {4, 19, 31}};

In[2]:= m /. {a_, b_, c_} /; b < c -> {a, c, b}

Out[2]= {{3, 25, 17}, {6, 33, 27}, {4, 29, 23}, {5, 37, 19}, {7, 35, 20}, {4, 31, 19}}
POSTED BY: Ilian Gachevski
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract