drjrm3
drjrm3

Reputation: 4718

How can I vectorize a large number of subtractions in Matlab

I have one array (the "true" cartesian coordinates) which is of size (natoms*3,1) where natoms is the number of atoms. I also have a large number (500,000) of observations stored in an array of size (nobs, natoms*3). Now, I want to create an array of the differences between all observations against the true coordinates. I would like to simply vectorize this by doing something like

for iat = 1:natoms
  xyz_dif = xyz_obs(:, 3*iat-2:3*iat) - xyz_true(3*iat-2:3*iat)
end

but this does not work. Instead I am forced to go through each of the observtions like so:

for iat = 1:natoms
  for iobs = 1:nobs
     xyz_diff(iobs, 3*iat-2:3*iat) = xyzs(iobs, 3*iat-2:3*iat) - xyz_true(3*iat-2:3*iat)
  end
end

but this seems quite inefficient. Is there a faster, more efficient way to do this?

Thanks.

Upvotes: 1

Views: 62

Answers (2)

user2041376
user2041376

Reputation:

an alternative solution, which in my view is more readable is to use matrix multiplication:

xyz_diff =  xyz_obs-ones(nobs,1)*xyz_true;

Upvotes: 2

Shai
Shai

Reputation: 114796

use bsxfun

 xyz_diff = bsxfun(@minus, xyz_true', xyz_obs)

Upvotes: 3

Related Questions