这个MATLAB脚本有没有更快的方法?

时间:2015-03-07 07:57:31

标签: performance matlab matrix

原始脚本是

    Y = [1 2 3 3 2 1 1 2 3]';
    n = length(Y);
    Ym = zeros(n, n);
    for i=1:n
        index = find(Y==Y(i));
        Ym(i, index') = 1;
    end

然后,Ym

    Ym =

 1     0     0     0     0     1     1     0     0
 0     1     0     0     1     0     0     1     0
 0     0     1     1     0     0     0     0     1
 0     0     1     1     0     0     0     0     1
 0     1     0     0     1     0     0     1     0
 1     0     0     0     0     1     1     0     0
 1     0     0     0     0     1     1     0     0
 0     1     0     0     1     0     0     1     0
 0     0     1     1     0     0     0     0     1

2 个答案:

答案 0 :(得分:3)

是的!使用bsxfun -

Ym = bsxfun(@eq,Y,Y.')

答案 1 :(得分:1)

我发现逻辑索引在我的计算机上比bsxfun工作得更快。这里是不同方法的采样时间:

tic;
for j=1:10000
    Y = [1 2 3 3 2 1 1 2 3]';
    n = length(Y);
    Ym = zeros(n, n);
    for i=1:n
        index = find(Y==Y(i));
        Ym(i, index') = 1;
    end
end
disp('Method 1:');
toc;

tic;
for j=1:10000
    Y = [1 2 3 3 2 1 1 2 3]';
    n = length(Y);
    Ym = zeros(n, n);
    for i=1:n
        Ym(i, Y==Y(i)') = 1;
    end
end
disp('Method 2:');
toc;
tic;
for j=1:10000
    Y = [1 2 3 3 2 1 1 2 3]';
    n = length(Y);
    Ym = zeros(n, n);
    a=repmat(Y,1,n);
    b=repmat(Y',n,1);
    Ym(a==b)=1;
end
disp('Method 3:');
toc;

tic;
for j=1:10000
    Y = [1 2 3 3 2 1 1 2 3]';
    Ym = bsxfun(@eq,Y,Y.');
end
disp('Method 4');
toc

输出:

Method 1:
Elapsed time is 0.111412 seconds.
Method 2:
Elapsed time is 0.069617 seconds.
Method 3:
Elapsed time is 0.246780 seconds.
Method 4
Elapsed time is 0.103120 seconds.