原始脚本是
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
答案 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.