Veridian
Veridian

Reputation: 3667

MATLAB How to get rid of loop for subtracting two arrays

I am trying to subtract two arrays in MATLAB of different sizes and I am currently using a for loop, which takes a long amount of time. Is there any way to make the code below faster? I'm wondering if maybe I can somehow create an array that is 117x489x489 in a fast way without the for loop.

The first array, a, has dimensions 1x117, the second array, b, has dimensions 489x489. The result matrix has dimensions 117x489x489.

Here is how I am subtracting the two arrays:

for i = 1:length(a)
  result(i) = a(i) - b;
end

Upvotes: 2

Views: 135

Answers (1)

Divakar
Divakar

Reputation: 221564

You can use efficient bsxfun here that avoids the loop by doing expansions of both a and b to a size of 117x489x489 and then performs elementwise subtraction under the hood. Thus, it presents a vectorized approach to achieve the desired result. Here's the code -

result = bsxfun(@minus,a(:),permute(b,[3 1 2]))

That (:) with a and permute with b helps in creating singleton dimensions for a and b respectively as needed for their respective expansions with bsxfun.


You can avoid permute there with some reshaping like so -

result = reshape(bsxfun(@minus,a(:),b(:).'),[numel(a) size(b)])

Upvotes: 6

Related Questions