我有两个数组,A和B.每行的第一个数字是序列号。
如何将A和B组合成一个数组C,以便A中具有相同序列号的所有行连接在一起……
我的方法如下,提取两个数组的前导数字并进行比较:
a=num2str(A)-'0'; b=num2str(B)-'0'; [ida,idb]=ismember(a(:,1),b(:,1));
现在得到的排序索引 A
A
[~,ids]=sort(a(:,1));
创建输出数组
C=zeros(size(A,1),2);
最后分配和排序输出
C(:,1)=A; C(ida,2)=B(idb(idb>0)); %sort result C=C(ids,:)
首先,整个脚本。乍一看,我没有使用循环找不到解决方案。
A = [ 12345; 47542; 32673; 65436; 75343; 23496; 54765; ] B = [ 23566; 33425; 65438; 75354; ] A = sort(A); % Sort A and B. B = sort(B); A_str = int2str(A); % Convert integers to chars. B_str = int2str(B); A_sn = A_str(:, 1); % Extract first columns. B_sn = B_str(:, 1); % Basically, these are the serial numbers. C = zeros(size(A, 1), size(A, 2) * 2); % Initialize C. C(:, 1) = A; % First column of C is just A. for i = 1:length(A_sn) % For all serial numbers in A... for j = 1:length(B_sn) % For all serial numbers in B... if (A_sn(i) == B_sn(j)) % Check if serial number in B equals the serial number in A. C(i, 2) = B(j); % If so, set i-th row in C to the corresponding value in B. end end end C
结果是:
A = 12345 47542 32673 65436 75343 23496 54765 B = 23566 33425 65438 75354 C = 12345 0 23496 23566 32673 33425 47542 0 54765 0 65436 65438 75343 75354