Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have a $3\times3$ matrix A, and a function sTrans that outputs two $3\times3$ matrices in a list when given a $3\times3$ matrix.

So the input

A = {{1,2,3} , {4,5,6} , {7,8,9}}

And the output

sTrans[A]

{ {{3, 1, 2}, {4, 5, 6}, {7, 8, 9}} , {{1, 2, 3}, {6, 4, 5}, {7, 8, 9} }}

And now I want to append the two matrices in a queue. The enQueue operation

enQueue[q_, elem_] := If[FreeQ[q,elem],qt++; q[[qt]]= elem]

How should I write the code without using loop? (P.S. I've heard multiple times that the whole concept of MMA is against For and While loops)

share|improve this question
add comment

1 Answer 1

up vote 2 down vote accepted

As I understand it you want to add elements to the end of the list if they don't already exist in the list. This is one way:

enQueue[q_, elements_] := Join[q, Complement[elements, q]]

If you just want to append elements Join alone will suffice. I'm confused because your code says "if element elem is not in q, then set qt=qt+1. If the element does already exist, set q[[qt]] to element." So it's like you only want duplicates in the queue and gaps in the list (perhaps filled with a default value?). Also you will overwrite the same position in q multiple times if several new elements appear in a sequence. To me this is non-sensical and to get proper help, if that's what you want to do, you need to give more details about the bigger picture.

Your question "how can I do this without loops" means you've realized that procedural programming is not the most efficient way to write Mathematica code, but you're still stuck in that way of thinking it seems since you're trying to write a function that handles each element separately. The functional style is more powerful often because of the fact that it doesn't handle elements individually, but rather handles an entire list at once like my example above where I give the function all the elements I want to append and in one fell swoop Mathematica handles the problem with two functions.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.