0
votes

In an effort to reduce usage of loops in my Matlab code, I'm trying to use elementwise multiplication to compute matrix values. Following is the code I initially had

for doc = 1:docs 
    for word = 1:words
        den =0;
        for topic = 1:topics
            posterior(topic,doc,word) =prior(1,topic)*expDoc(doc,topic)*expWord(word,topic);
            den  = den + posterior(topic,doc,word) ;
        end     
    end
end

With reference to a similar question. Following is my attempt

 posterior(1:topics,1:docs,1:words) = prior(1,1:topics).*expDoc(1:docs,1:topics).*expWord(1:words,1:topics);
 den = sum(posterior(:,:,:));
 posterior(:,:,:)  =  posterior(:,:,:)/(den);

However, as required for elementwise operations, how do I ensure that the multiplcation is done with matrices of same dimensions?

1
Your attempt wont work, because prior, expDoc and expWord are all 2D arrays, so you can't use element-wise multiplication to get a 3D array. Think carefully about what is being multiplied together. - David
Ok, so how would you go about optimizing the for loops? - Ashwini Khare

1 Answers

1
votes

You may be able to get this to work through careful use of bsxfun and permute. permute is used to rearrange the order of the dimensions of a matrix - we'll use this to rearrange your variables to get them in the right order to multiply them using bsxfun.

From what I can tell, you have three variables:

prior, size == [1,topics];
expDoc, size == [docs,topics];
expWord, size == [words,topics];

and you want to get a final variable:

posterior, size == [topics,docs,words]

I think you should be able to get the matrix posterior by using the following method:

prior_perm = prior.';
expDoc_perm = expDoc.';
expWord_perm = permute(expWord,[2,3,1]);

posterior = bsxfun(@times,prior_perm,bsxfun(@times,expDoc_perm,expWord_perm));

den = sum(posterior(:));

You will want to make sure to test this produces the right output though, as I haven't.