Path: news.mathworks.com!not-for-mail From: <HIDDEN> Newsgroups: comp.soft-sys.matlab Subject: Re: Column Operations Matlab Date: Sat, 26 Jun 2010 04:24:04 +0000 (UTC) Organization: The MathWorks, Inc. Lines: 37 Message-ID: <i03vd4$hvg$1@fred.mathworks.com> References: <i03r9s$47$1@fred.mathworks.com> Reply-To: <HIDDEN> NNTP-Posting-Host: webapp-05-blr.mathworks.com Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: fred.mathworks.com 1277526244 18416 172.30.248.35 (26 Jun 2010 04:24:04 GMT) X-Complaints-To: news@mathworks.com NNTP-Posting-Date: Sat, 26 Jun 2010 04:24:04 +0000 (UTC) X-Newsreader: MATLAB Central Newsreader 1187260 Xref: news.mathworks.com comp.soft-sys.matlab:648174 "Donatello " <Manguaco7@hotmail.com> wrote in message <i03r9s$47$1@fred.mathworks.com>... > plz i need the script to change the columns of a matrix > example > 1 2 3 3 2 1 > 4 5 6 ---------------> 6 5 4 > 7 8 9 9 8 7 > this is my code.... > > function invier=cambifil(A) > [f,c]=size(A); > for i=1:f; > for j=1:c; > A(i,c-j+1)=A(i,j); > end > end > invier=A - - - - - - - - - - Matt's code will work but I'm afraid your code will not, Donatello. The trouble is that when you do A(i,c-j+1)=A(i,j) for i = 1, j = 1, and c = 3, the value 3 that currently resides in A(1,3) will be overwritten by a 1. Then subsequently when i = 1, j = 3, the value at A(1,3) which was previously a 3 is now the 1 that was written into it. Hence the 3 value is lost forever and you will not be able to place it into A(1,1). Matt's code is superior, but it would be instructive for you to see how your for-loop method could be made to work. c2 = floor(c/2); for i = 1:f for j = 1:c2 t = A(i,j); % Temporary storage A(i,j) = A(i,c-j+1); A(i,c-j+1) = t; % The swap is complete end end This way you interchange the two values to be swapped before either is destroyed by providing a temporary storage for one of them. It is an easy kind of mistake for beginners to make in rearranging or modifying the contents of matrices. They sometimes forget that in for-loops these changes do not all occur simultaneously but rather one at a time. With vectorized techniques as for example Matt's, changes are automatically stored in special temporary buffers until they are complete and then the result is written out, which avoids the overwriting trouble. With your for-loops you could also accomplish the same thing by writing the reversed data into a temporary matrix T leaving A untouched and then finally finishing with A = T; Roger Stafford