Matlab:我如何执行行操作而不用蛮力for循环? [英] Matlab: how can I perform row operations without brute-force for loop?

查看:333
本文介绍了Matlab:我如何执行行操作而不用蛮力for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  N1 = size(X,1); 
N2 = size(Xtrain,1);
Dist =零(N1,N2); (i,j)= D-sum(X(i,:)== Xtrain(j)(1):

对于i = 1:N1
对于j = 1: ,:));
end
end

(X和Xtrain是稀疏的逻辑矩阵) >

它工作正常,并通过测试,但我相信这不是非常优化和写得很好的解决方案。



我可以使用一些构建的Matlab函数来改进这个函数吗?对于Matlab来说,我绝对是新手,所以我不知道是否真的有机会让它更好。 解决方案

你想学习矢量化,这里有一些代码来比较不同的实现这种成对的距离。

首先我们建立两个二进制矩阵作为输入(其中每行是一个实例):

  m = 5; 
n = 4;
p = 3;
A = double(rand(m,p)> 0.5);
B = double(rand(n,p)> 0.5);



1。在每对实例上进行双循环

$ $ $ $ $ $ $ $ D $ =零(m,n); (i,j)= B(j,:))/ p(i,j)= ;
end
end



2。 PDIST2



  D1 = pdist2(A,B,'hamming'); 



3。在每个实例上针对所有其他实例的单循环



  D2 =零(m,n); 
for i = 1:n
D2(:,i)= sum(bsxfun(@ne,A,B(i,:)),2)./ p;
end



4。使用网格索引进行矢量化,全部针对所有

  D3 =零(m,n); 
[x,y] = ndgrid(1:m,1:n);
D3(:) = sum(A(x(:),:)〜= B(y(:),:),2)./ p;



5。向量化在第三维,所有对所有

  D4 = sum(bsxfun(@ne,A,reshape(B。', 1 pn])),2)./ p; 
D4 =置换(D4,[1 3 2]);

最后我们比较所有方法是否相等

  assert(isequal(D0,D1,D2,D3,D4))


I need to do function that works like this :

N1 = size(X,1);
N2 = size(Xtrain,1);
Dist = zeros(N1,N2);

    for i=1:N1
        for j=1:N2
            Dist(i,j)=D-sum(X(i,:)==Xtrain(j,:));
        end
    end

(X and Xtrain are sparse logical matrixes)

It works fine and passes the tests, but I believe it's not very optimal and well-written solution.

How can I improve that function using some built Matlab functions? I'm absolutely new to Matlab, so I don't know if there really is an opportunity to make it better somehow.

解决方案

You wanted to learn about vectorization, here some code to study comparing different implementations of this pair-wise distance.

First we build two binary matrices as input (where each row is an instance):

m = 5;
n = 4;
p = 3;
A = double(rand(m,p) > 0.5);
B = double(rand(n,p) > 0.5);

1. double-loop over each pair of instances

D0 = zeros(m,n);
for i=1:m
    for j=1:n
        D0(i,j) = sum(A(i,:) ~= B(j,:)) / p;
    end
end

2. PDIST2

D1 = pdist2(A, B, 'hamming');

3. single-loop over each instance against all other instances

D2 = zeros(m,n);
for i=1:n
    D2(:,i) = sum(bsxfun(@ne, A, B(i,:)), 2) ./ p;
end

4. vectorized with grid indexing, all against all

D3 = zeros(m,n);
[x,y] = ndgrid(1:m,1:n);
D3(:) = sum(A(x(:),:) ~= B(y(:),:), 2) ./ p;

5. vectorized in third dimension, all against all

D4 = sum(bsxfun(@ne, A, reshape(B.',[1 p n])), 2) ./ p;
D4 = permute(D4, [1 3 2]);

Finally we compare all methods are equal

assert(isequal(D0,D1,D2,D3,D4))

这篇关于Matlab:我如何执行行操作而不用蛮力for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆