Frage

I want to swap half of the elements of an array A with corresponding half of elements of another array B.Is there any built-in function for this operation or is there any shortcut ???Can anyone help me ????

k=1; 
for i=1:nwpc 
    for j=i+1:nwpc 
        if(i<j) nwP3(k,1:cross_pt)=nwP1(i,1:cross_pt)       
            nwP3(k,cross_pt+1:pc)=nwP1(j,cross_pt+1:pc); 
            k=k+1;
            nwP3(k,1:cross_pt)=nwP1(j,1:cross_pt);    
            nwP3(k,cross_pt+1:pc)=nwP1(i,cross_pt+1:pc); 
            k=k+1; 
         end 
     end
end

Example: input

A={1 2 3 4 5 6};
B={7,8,9,10,11,12}; 

output

C=={1,2,3,10,11,12}
D=={7,8,9,4,5,6}
War es hilfreich?

Lösung

Well, it's Friday after all...Here's half a dozen ways:

%// Method 0: beginning programmer
for i=0:1:2
    c=A(i);
    A(i)=B(i);
    B(i)=c;
end


%// Method 1: MATLAB novice
[A,B] = deal([B(1:3) A(4:end)], [A(1:3) B(4:end)]);


%// Method 1.5: MATLAB novice+        
[A(1:3), B(1:3)] = deal(B(1:3), A(1:3));


%// Method 1.8: ambitious MATLAB novice
function myFunction(A,B)
    %//...
    [A(1:3), B(1:3)] = swap(A(1:3), B(1:3));
    %//...


function [a,b] = swap(b,a)
    % look, no content needed!


%// Method 2: Freshman CS student looking to impress friends
A(1:3) = A(1:3)+B(1:3);
B(1:3) = A(1:3)-B(1:3);   %// Look, no temporary!  
A(1:3) = A(1:3)-B(1:3);   %// Overflow? Pff, that won't ever happen.


%// Method 3: Overambitious CS master forced to use MATLAB  
#include "mex.h"
void mexFunction(int nlhs,       mxArray *plhs[], 
                 int nrhs, const mxArray *prhs[])
{         
    plhs[0]=prhs[1];  // (generated with AutoHotKey)
    plhs[1]=prhs[0];
}


%// Method 4: You and way too many others
1. Go to http://www.stackoverflow.com
2. Ask "the internet" how to do it.
3. Wait until "the internet" has done your work for you.
5. Repeat from step 1 for every new question that pops up.


%// Method 5: GOD HIMSELF!
C = A(1:3);      %// ...will simply use a temporary
A(1:3) = B(1:3);  
B(1:3) = C;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top