1

いくつかのクラスター センターといくつかのデータ ポイントがあります。以下のように距離を計算したい(ノルムはユークリッド距離用です):

            costsTmp = zeros(NObjects,NClusters);
            lambda = zeros(NObjects,NClusters);
            for clustclust = 1:NClusters
                for objobj = 1:NObjects
                    costsTmp(objobj,clustclust) = norm(curCenters(clustclust,:)-curPartData(objobj,:),'fro');
                    lambda(objobj,clustclust) = (costsTmp(objobj,clustclust) - log(si1(clustclust,objobj)))/log(si2(objobj,clustclust));
                end
            end

このスニペットをベクトル化するにはどうすればよいですか? ありがとう

4

2 に答える 2

2

このベクトル化は、 を使用して非常にエレガントに (そう言えば) 行うことができますbsxfun。sは必要ありませrepmat

costsTemp = bsxfun( @minus, permute( curCenters, [1 3 2] ), ...
                            permute( curPartData, [3 1 2] ) );
% I am not sure why you use Frobenius norm, this is the same as Euclidean norm for vector
costsTemp = sqrt( sum( costsTemp.^2, 3 ) ); % now we have the norms
lambda = costsTmp -reallog(si1)./reallog(si2);

出力をまったく同じにするために、次元ベクトルの順序を少し変更する必要がある場合がありますpermute(転置に関して)。

于 2012-11-30T07:30:37.753 に答える
2

これを試して:

    Difference = zeros(NObjects,NClusters);
    costsTmp = zeros(NObjects,NClusters);
    lambda = zeros(NObjects,NClusters);
    for clustclust = 1:NClusters
    repeated_curCenter = repmat(curCenter(clustclust,:), NObjects, 1); 
    % ^^ This creates a repeated matrix of 1 cluster center but with NObject
    % rows. Now, dimensions of repeated_curCenter equals that of curPartData

    Difference(:,clustclust) = repeated_curCenter - curPartData;
    costsTmp(:,clustclust) = sqrt(sum(abs(costsTmp(:,clustclust)).^2, 1)); %Euclidean norm
    end

アプローチは、等しい次元の行列を作成しようとすることです。次のように 2 つの 3D 配列を作成してこの概念を拡張することにより、現在の for ループを排除することもできます。

costTmp = zeros(NObjects,NClusters); lambda = zeros(NObjects,NClusters);

    %Assume that number of dimensions for data = n
    %curCenter's dimensions = NClusters x n
    repeated_curCenter = repmat(curCenter, 1, 1, NObjects);
    %repeated_curCenter's dimensions = NClusters x n x NObjects

    %curPartData's dimensions = NObject x n
    repeated_curPartData = repmat(curPartData, 1, 1, NClusters);
    %repeated_curPartData's dimensions = NObjects x n x NClusters

    %Alligning the matrices along similar dimensions. After this, both matrices
    %have dimensions of NObjects x n x NClusters
    new_repeated_curCenter = permute(repeated_curCenter, [3, 2, 1]);

    Difference = new_repeated_curCenter - repeated_curPartData;

    Norm = sqrt(sum(abs(Difference)).^2, 2); %sums along the 2nd dimensions i.e. n
    %Norm's dimensions are now NObjects x 1 x NClusters. 

    Norm = permute(Norm, [1, 3, 2]);

ここで、Norm は costTmp のようなものですが、追加の次元があります。ラムダのコードを提供していません。質問のコードにもラムダが何であるかわかりません。

于 2012-11-30T05:24:52.663 に答える