# instruction version of colon operator (:)

10 views (last 30 days)

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!

##### 0 Comments

### Accepted Answer

Cedric Wannaz
on 7 Sep 2013

Edited: Cedric Wannaz
on 7 Sep 2013

The way I am managing this is to use RESHAPE, which doesn't realloc or build temp array(s) as far as I could see. So what you do with vec(A) in Octave, should be achievable with reshape(A,1,[]) in MATLAB.

I made the following test on my laptop to check: I setup a watchdog with Process Lasso which kills MATLAB when it uses more RAM than what is available (just so I am not stuck swapping), and built a matrix A a little larger than half the size of the RAM available..

>> A = rand(2e4) ; % 8*(2e4)^2 > half the 5GB avail. on my laptop 8GB.

I then performed the reshape..

>> A = reshape(A, 1, []) ;

which didn't decrease the RAM available, and wasn't killed by Process Lasso. Sometimes we can't see a glitch in RAM usage, which is why I chose to build a case where any realloc or creation of temp array(s) would lead to swapping. Moreover, even without the slow down of swapping, Process Lasso would have caught any glitch in memory usage and killed MATLAB, which didn't happen.

So the following should work:

A = sum( reshape( o(:,:,n).*o(:,:,m), 1, [] )) ;

##### 5 Comments

Cedric Wannaz
on 8 Sep 2013

I am using both (:) and RESHAPE, the first when I can index the object, and the second when I cannot (which is your case). As you mention, both are useful to ensure that we are dealing with column vectors (without using a lengthy statement if size(x,1)==1, .. else .. end), e.g. in functions when we want to allow users submitting both row and column vectors.

Now they are not equivalent, as (:) is linear indexing and RESHAPE is not (yet it is more versatile). It matters especially from an OOP prospective as (:) can be caught with overloads of indexing methods SUBSREF/SUBSASGN, and RESHAPE should be overloaded on its own.

NOTE: I should have written reshape(A,[],1) in my first answer, as you corrected in your comment.

### 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

### See Also

### Products

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!