2

这是我想要执行的一项相当简单的任务,但我似乎无法找到一种方法来完成它。我尝试过 sortrows、reshaping 和其他解决方案,但没有一个完全符合我的要求。

本质上,我有两个向量来自相同的值范围,长度不等。有些值是相等的,有些不是。例如

A = [1 5 20 30 53 70 92]
B = [2 3 4 16 20 30 60 95 100]

我想要做的是在每个向量中添加“NaN”,以“代替”另一个向量中未共享的值。所以,我希望它们看起来像:

A = [1 NaN NaN NaN 5 NaN 20 30 53 NaN 70 92 NaN NaN]
B = [NaN 2 3 4 NaN 16 20 30 NaN 60 NaN NaN 95 100]

向量将具有用于另一个向量的值的占位符的某种方法。

我是否合并向量,对其进行排序,然后以某种方式搜索并用 NaN 替换来自另一个向量的所有值?这似乎是一个笨拙的解决方案,尽管并非不可能。我觉得有一些更优雅的方式来完成我所缺少的。

谢谢!

4

2 回答 2

4

这是使用简单地图的一种解决方案:

A = [1 5 20 30 53 70 92]
B = [2 3 4 16 20 30 60 95 100]

% map all A and B elements
% use 1 for A and 2 for B
map = zeros(max([A,B]),1);
map(A) = 1;
map(B) = bitor(map(B), 2);

% find the values present in either A, or B
[~,~,j] = find(map);
AA = nan(size(j));
BB = nan(size(j));
AA(bitand(j,1)~=0) = A;
BB(bitand(j,2)~=0) = B;

与 Rodys 解决方案的比较表明这种方法要快一些:

A = unique(randi(10000, 1000, 1));
B = unique(randi(10000, 1000, 1));

tic;
for i=1:1000
    map=zeros(10000,1);
    map(A) = 1;
    map(B) = bitor(map(B), 2);
    [~,~,j] = find(map);
    AA = nan(size(j));
    BB = nan(size(j));
    AA(bitand(j,1)~=0) = A;
    BB(bitand(j,2)~=0) = B;
end
toc


tic
for i=1:1000
    C = union(A,B);
    Ap = NaN(size(C));   
    Ap(ismember(C,A)) = A;
    Bp = NaN(size(C));   
    Bp(ismember(C,B)) = B;
end
toc

isequalwithequalnans(BB, Bp)
isequalwithequalnans(AA, Ap)

Elapsed time is 0.283828 seconds.
Elapsed time is 0.457204 seconds.

ans =
 1

ans =
 1
于 2012-12-06T16:03:04.057 回答
3

好吧,这是一种方法:

% union of sets A and B
C = union(A,B);

% initialize new sets, check membership, and 
% assign old values when applicable
Ap = NaN(size(C));   Ap(ismember(C,A)) = A;
Bp = NaN(size(C));   Bp(ismember(C,B)) = B;

请注意,union摆脱重复。如果您想保留所有重复,请使用手册sort和第二个输出ismember

% combine and sort, KEEPING repetitions
C = sort([A B]);

% initialize new sets, check membership, and 
% assign old values when applicable
Ap = NaN(size(C));         Bp = NaN(size(C));  
[I,Ab] = ismember(C,A);    [I,Bb] = ismember(C,B);
Ap(I) = A(Ab(I));          Bp(I) = B(Bb(I));
于 2012-12-06T16:02:09.150 回答