instruction version of colon operator (:)
Show older comments
I have the following situation:
A = sum(sum(o(:,:,n).*o(:,:,m)));
which I would like to vectorize further during the summation.
In GNU Octave there is the vec command which works like
A(:) % = vec(A)
which would allow:
A = sum(vec(o(:,:,n).*o(:,:,m)));
Thus my question is if there is a similar command in Matlab? I know I could use resize or myvec = @(x) x(:) or other more complicated constructs. I am looking for the instruction version of the (:) operator. Alternatively, is there a better way to sum all elements in a matrix?
Thanks ahead!
Accepted Answer
More Answers (1)
Image Analyst
on 7 Sep 2013
array2D = o(:,:,n) .* o(:,:,m);
% Turn array2D into a vector with (:)
% then you need only one sum().
theSum = sum(array2D(:));
7 Comments
Image Analyst
on 7 Sep 2013
Edited: Image Analyst
on 7 Sep 2013
By the way, to get a vector like you did, the equivalent line of code in MATLAB looks like
vec = array2D(:);
Then you could do
theSum = sum(vec);
Christian
on 7 Sep 2013
Image Analyst
on 7 Sep 2013
Why do you need to prevent an extra copy / temporary variable?
Christian
on 7 Sep 2013
Image Analyst
on 7 Sep 2013
I don't think there's a way to vectorize the code and avoid either you explicitly making a temporary variable or MATLAB secretly making an internal copy unbeknownst to you, but I could be wrong. Alternative would be to access elements one at a time via indexing but that would probably be slower especially for your gigantic matrices. By the way, how big are they? How many rows and columns? Thousands, like they're a big high-res image?
Christian
on 7 Sep 2013
Image Analyst
on 7 Sep 2013
OK, I was just wondering because often we see students, who normally work with arrays with only around 10 columns, refer to a 1000x1000 matrix as "huge", or who have a for loop that takes only a few microseconds spending billions of times that amount of time to vectorize it to save a few nanoseconds - something that will never be noticed. But it sounds like you know what you're talking about and you could be in trouble if your array takes up hundreds of megabytes. Sorry I didn't have good news for you.
Categories
Find more on Dates and Time in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!