将一半数组元素与另一个数组交换一半

时间:2014-03-14 09:05:25

标签: matlab cell-array

我想将数组A的一半元素与另一个数组B的相应一半元素交换。是否有任何内置函数用于此操作或者是否有任何快捷方式???任何人都可以帮助我??? ?

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

实施例: 输入

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

输出

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

1 个答案:

答案 0 :(得分:5)

嗯,毕竟是星期五......这里有六种方式:

%// 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;