Functional form of the colon (:) operator?

조회 수: 26 (최근 30일)
Knut
Knut 2012년 9월 18일
댓글: Royi Avital 2019년 1월 15일
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));

채택된 답변

José-Luis
José-Luis 2012년 9월 18일
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
Jan
Jan 2017년 10월 10일
Nice, short, efficient: I have accepted this answer.

댓글을 달려면 로그인하십시오.

추가 답변 (3개)

Daniel Shub
Daniel Shub 2012년 9월 18일
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.

Royi Avital
Royi Avital 2017년 10월 10일
I really wish MATLAB would add function to vectorize arrays into column vector as the colon operator does.
  댓글 수: 3
Jan
Jan 2017년 10월 10일
편집: Jan 2017년 10월 10일
@Royi: Do you have an example where the mentioned methods are not applicable or "ugly"?
Royi Avital
Royi Avital 2019년 1월 15일
@Jan, I find something like vec(A) to be much more elegant.

댓글을 달려면 로그인하십시오.


Jan
Jan 2017년 10월 10일
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
Walter Roberson
Walter Roberson 2018년 10월 17일
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))

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by