Functional form of the colon (:) operator?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Knut
am 18 Sep. 2012
Kommentiert: Royi Avital
am 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 Kommentare
Akzeptierte Antwort
José-Luis
am 18 Sep. 2012
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 Kommentar
Weitere Antworten (3)
Daniel Shub
am 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 Kommentare
Royi Avital
am 10 Okt. 2017
I really wish MATLAB would add function to vectorize arrays into column vector as the colon operator does.
3 Kommentare
Jan
am 10 Okt. 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 Kommentar
Walter Roberson
am 17 Okt. 2018
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))
Siehe auch
Kategorien
Mehr zu Performance Profiling finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!