user1285419
user1285419

Reputation: 2225

seeking a way use non-looping method for calculation in matlab

I am porting a c program to matlab for simulation of some mathematical problem. I have all the code rewritten in matlab but I found there spent too much time in one loop. I don't know if there is any better way to calculate the following instead of using a for statement

I have about 1000 matrices (all of the same dimension) defined within a structure

A{1} = matrix1 A{2} = matrix2 ... A{1000} = matrix1000

B is a constant matrix of the same dimension of A{n}

I want to calculate the element-by-element production of A{n} and B and return the total sum of all resulting elements to

for k=1:1000
  AllSum(k) = sum(sum(A{k}.*B))
end

the size of A depends on the parameter, the typical size is 300x300. If I run the above loop for once, the speed is ok. But that loop will be executed within another block which will be called for many times so it takes quite a long time to find all the sum. I wonder if there is any way to boost it. Thanks

Upvotes: 1

Views: 123

Answers (2)

Peter
Peter

Reputation: 14927

Agreed that you should use a 3d matrix instead of cell.

What does sum of product remind you of? Dot product. What does a series of dot products remind you of? vector-matrix multiply. So what you want to do is reshape your data so that each column of your matrix is one unwrapped A{k}, and your B row-vector is your unwrapped B matrix. In other words, the fact that A and B are 2D is irrelevant to your computation.

If you convert A to A(:,:,k) = A{k} as recommended, then:

vec = B(:).';
mtx = reshape(A, size(A,1)*size(A,2), size(A,3));
AllSum = vec*mtx;

Upvotes: 1

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

In your specific case, you can calculate the sum of all A matrixes first, then multiply by B. Instead of defining A as cell array, define them as one 3d array: (I agree on this one with @SeçkinSavaşçı)

A(:,:,i) = ...

Instead of:

A{i} = ...

Then, sum and multiply by B:

result = sum(A,3).* B;

Upvotes: 1

Related Questions