MATLAB Answers

Knut
0

Functional form of the colon (:) operator?

Asked by Knut
on 18 Sep 2012
Latest activity Commented on by Royi Avital on 15 Jan 2019
This is a post about "how to write neat, efficient, readable MATLAB code". I get the job done by doing work-arounds, but I would rather not do those.
Assume that a, b are two vectors of unknown orientation, and we want to compute something similar to the dot-product.
It might look something like this:
function y = myfunc(a,b)
//make sure that vectors are oriented the same way
y = a(:) .* b(:);
But what if I need to calculate y for elements 2:N? We might do something like this, but I think it clutters the code:
function y = myfunc(a,b)
a = a(2:end)
b = b(2:end)
y = a(:) .* b(:);
I am wishing for a functional form of the colon operator that might look something like this:
function y = myfunc(a,b)
y = colon(a(2:end)) .* colon(b(2:end));

  0 Comments

Sign in to comment.

4 Answers

Answer by José-Luis
on 18 Sep 2012
 Accepted Answer

function y = myfunc(a,b)
//make sure that vectors are oriented the same way
y = reshape(a(2:end),[],1) .* reshape(b(2:end),[],1);

  1 Comments

Jan
on 10 Oct 2017
Nice, short, efficient: I have accepted this answer.

Sign in to comment.


Answer by Daniel Shub
on 18 Sep 2012

I thought that squeeze would do what you want, but apparently it doesn't "work" on row vectors. What would be nice is if squeeze had a row flag. Barring that, you can easily create your own colon function. From
type squeeze
it should be obvious what you need to change.

  0 Comments

Sign in to comment.


Answer by Royi Avital on 10 Oct 2017

I really wish MATLAB would add function to vectorize arrays into column vector as the colon operator does.

  3 Comments

We did, a very long time ago. It's called reshape.
A = magic(5);
B = reshape(A, [], 1);
% or to avoid the need to implicitly compute the "missing" size
% inside reshape
C = reshape(A, numel(A), 1);
Jan
on 10 Oct 2017
@Royi: Do you have an example where the mentioned methods are not applicable or "ugly"?
@Jan, I find something like vec(A) to be much more elegant.

Sign in to comment.


Answer by Jan
on 10 Oct 2017

What's wrong with:
y = x(:)
or:
reshape(x, [], 1)
There is a functional form of the x(:) operator:
subsref(x, struct('type', '()', 'subs', {{':'}}))

  1 Comments

Sometimes it is easiest to define an auxillary function, such as
column = @(M) M(:);
after which you can
column(a(2:end)) .* column(b(2:end))

Sign in to comment.



Translated by