Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7577777
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T17:16:28+00:00 2026-05-30T17:16:28+00:00

I have a piece of code which performs calculations on a matrix by iterating

  • 0

I have a piece of code which performs calculations on a matrix by iterating through its rows and columns. The piece of calculus performed is a cosine distance measure, with a code I found on Internet (could not retrieve the link right now).

There can be 10,000 rows and col. The matrix is symmetric so I just need to iterate half of it. Values are float.

The problem: it is very slow (will take 3 to 6 hours it seems). Can anyone point me to improvements? Thx!

Note on the code: it uses an abstract class for flexibility: this way, the cosine calculation defined in a separate class could be easily replaced by another one.

The code:

import Jama.Matrix;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.concurrent.ExecutionException;

public abstract class AbstractSimilarity {

    HashSet<Triple<Double, Integer, Integer>> set = new HashSet();
    public ArrayList<Thread> listThreads = new ArrayList();

    public void transform(Matrix matrixToBeTransformed) throws InterruptedException, 
ExecutionException {

        int numDocs = termDocumentMatrix.getColumnDimension();

        Main.similarityMatrix = new Matrix(numDocs, numDocs);

        System.out.println("size of the matrix: " + numDocs + "x " + numDocs);

        //1. iteration through all rows of the matrixToBeTransformed
        for (int i = numDocs - 1; i >0 ; i--) {
            System.out.println("matrix treatment... " + ((float) i / (float) numDocs * 100) + "%");

            //2. isolates the row i of this matrixToBeTransformed
            Matrix sourceDocMatrix = matrixToBeTransformed.getMatrix(
                    0, matrixToBeTransformed.getRowDimension() - 1, i, i);



            // 3. Iterates through all columns of the matrixToBeTransformed
//            for (int j = 0; j < numDocs; j++) {
//                if (j < i) {
//
//                    //4. isolates the column j of this matrixToBeTransformed
//                    Matrix targetDocMatrix = matrixToBeTransformed.getMatrix(
//                            0, matrixToBeTransformed.getRowDimension() - 1, j, j);


                    //5. computes the similarity between this given row and this given column and writes it in a resultMatrix
//                    Main.resultMatrix.set(i, j, computeSimilarity(sourceDocMatrix, targetDocMatrix));
//                } else {
//                    Main.resultMatrix.set(i, j, 0);

//                }
//
//            }
        }

The class which defines the computation to be done:

import Jama.Matrix;

public class CosineSimilarity extends AbstractSimilarity{

  @Override
  protected double computeSimilarity(Matrix sourceDoc, Matrix targetDoc) {
    double dotProduct = sourceDoc.arrayTimes(targetDoc).norm1();
    double eucledianDist = sourceDoc.normF() * targetDoc.normF();
    return dotProduct / eucledianDist;
  }

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T17:16:29+00:00Added an answer on May 30, 2026 at 5:16 pm

    You appear to be dealing with a n^3 algorithm. n^2 because you’re filling a (half) matrix. Times n again because the methods to fill each element(dot product/fnorm) take time n. The good news is that because the calculations don’t depend on each other, you could multithread this to speed it up.

    public class DoCalc extends Thread
    {
      public Matrix localM;
      int startRow;
      int endRow;
      public DoCalc(Matrix mArg, int startArg, int endArg)
      {
        localM=mArg;
        startRow=startArg;
        endRow=endArg;
      }
    
      public void doCalc()
      {
        //Pseudo-code
        for each row from startRow to endRow
          for each column 0 to size-1
            result[i][j] = similarityCalculation
      }
      public void run()
      {
        doCalc();
      }
    }
    
    public void transform(Matrix toBeTransformed)
    {
      int numDocs = termDocumentMatrix.getColumnDimension();
    
      Main.similarityMatrix = new Matrix(numDocs, numDocs);
      Vector<DoCalc> running = new Vector<DoCalc>();
      int blockSize = 10;
      for (int x = 0; x < numDocs-1;x+=blockSize)
      {
        DoCalc tempThread = new DoCalc(toBeTransformed,x,(x+blockSize>numDocs-1)?numDocs-1:x+blockSize);
        tempThread.start();
        running.add(tempThread);
      }
    
      for (DoCalc dc : running)
        dc.join();
    
    }
    

    Important notes:

    This is a very naive implementation. If you try to run it with arrays of your size, it will spawn 1000 threads. You can either fiddle with the blockSize or look into thread pooling.

    At best this will give you a multiple times increase in speed, 4x etc. If you want order of magnitude gains, you will need to properly profile and/or change your algorithm to something more efficient. Given the task you’re trying to perform(running a relatively expensive task on each element in a Matrix), the latter may not be possible.

    Edit: Multithreading will only increase speed significantly if you are cpu bound and have a multicore cpu with cores sitting relatively idle.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this piece of code which I'm hoping will be able to tell
I am somewhat new to R, and i have this piece of code which
I have the following piece of code which replaces template markers such as %POST_TITLE%
I have a piece of code with a) which I replaced with b) purely
I have a little piece of rails code which lets users enter a review.
I have a piece of code in ANSI C which uses the time.h library
I have a piece of fortran code, and I am not sure which standard
I have piece of code which I use to format a range of cells
I have a piece of code which will find out the repeating elements in
I have following piece of code which tries to load an XML file from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.