Be the first to rate this file! 19 downloads (last 30 days) File Size: 1.68 KB File ID: #12239

SWAP

by Jos (10584)

 

11 Sep 2006 (Updated 13 Sep 2006)

Code covered by the BSD License  

swap contents of two variables

Download Now | Watch this File

File Information
Description

SWAP(A,B) puts the contents of variable A into variable B and vice versa. You can use either function syntax 'swap(A,B)' or command syntax 'swap A B'.
 
Example:
   A = 1:4 ; B = 'Hello' ;
   swap(A,B) ;
   A % -> Hello
   B % -> 1 2 3 4
   swap A B ; % and back again ...
 
SWAP(A,B) is a convenient easy short-cut for other (series of) commands that have the same effect,e.g.,

  temp=A ; A=B ; B=temp ; clear temp ;
  [B,A] = deal(A,B) ;

The advantage over these two methods is that using SWAP one does not have to declare intermediate variables or worry about output.

MATLAB release MATLAB 6.5 (R13)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (3)
12 Sep 2006 Carlos Lopez

Why the following one-line function might not serve the same purpose?
function [y,x]=swap(x,y)

13 Sep 2006 Jos vdG

"function [y,x]=swap(x,y)" does not serve the same purpose, e.g., when it is called
like
A = 1 ; B = 'xx' ;
[C,D] = swap(A,B)

This will just create two new variables C and D, and does not swap A and B ...

13 Sep 2006 urs (us) schwarz

another one of the many solutions
format debug; % show the address asignments
a=1 % note the PR address
b='b';
[a,b]=deal(b,a)

us

Please login to add a comment or rating.
Updates
13 Sep 2006

1. Use <deal> to swap (insight from US)
2. Added command syntax functionality (suggested by DH)
3. Modified help section

Tag Activity for this File
Tag Applied By Date/Time
swap Jos (10584) 22 Oct 2008 08:38:55
replace Jos (10584) 22 Oct 2008 08:38:55
contents Jos (10584) 22 Oct 2008 08:38:55
syntax Jos (10584) 22 Oct 2008 08:38:55
utilities Jos (10584) 22 Oct 2008 08:38:55
 

MATLAB Central Terms of Use

NOTICE: Any content you submit to MATLAB Central, including personal information, is not subject to the protections which may be afforded information collected under other sections of The MathWorks, Inc. Web site. You are entirely responsible for all content that you upload, post, e-mail, transmit or otherwise make available via MATLAB Central. The MathWorks does not control the content posted by visitors to MATLAB Central and, does not guarantee the accuracy, integrity, or quality of such content. Under no circumstances will The MathWorks be liable in any way for any content not authored by The MathWorks, or any loss or damage of any kind incurred as a result of the use of any content posted, e-mailed, transmitted or otherwise made available via MATLAB Central. Read the complete Terms prior to use.

Contact us at files@mathworks.com