GEBRU
GEBRU

Reputation: 529

vectorize a constant function in octave

I am having this existential trouble trying to define a constant funcion that takes a vector as an argument:

I want to define a function like:

>f=@(x) 0.0;           % a constant function (zero or any other constant value).
>xx=linspace(0,10,10); % ten values where I want to evaluate the function

and when I run it, I get:

>> f(xx)
ans = 0

And I really was expecting a vector of zeros. (I dont see how to incorporate the vectorization feature into a constant function)

Does anyone have the soluction for this simple issue? Thanks in advance!

Upvotes: 1

Views: 251

Answers (2)

Nick J
Nick J

Reputation: 1610

ok, so from the comments above you want a function that will return an array the same size as the input, but with all values equal to some predefined constant.

@Luis's method above will work. I'm not sure about Matlab these days, but in older versions at least and in Octave repmat isn't the fastest, and there are other, lower overhead ways of generating repeated arrays. If it's a function that may get called a lot, I prefer to use ones() array expansion. (It also combines with broadcasting well, not that that's necessary in this case).

E.g.:

>> f = @(x)  repmat(5,size(x));

>> f([10 20 30; 40 50 60])
ans =
     5     5     5
     5     5     5

>> g = @(x) 5*ones(size(x));

>> g([10 20 30; 40 50 60])
ans =
     5     5     5
     5     5     5

doing a quick and dirty loop to estimate time requirement, we see that in Octave 5.2.0 the repmat version takes about 5x longer for the same operations:

>> tic;for idx = 1:1e4, f(rand(4,2,3));endfor,toc
Elapsed time is 1.54 seconds.

>> tic;for idx = 1:1e5, f(rand(4,2,3));endfor,toc
Elapsed time is 17.6487 seconds.

>> tic;for idx = 1:1e4, g(rand(4,2,3));endfor,toc
Elapsed time is 0.337171 seconds.

>> tic;for idx = 1:1e5, g(rand(4,2,3));endfor,toc
Elapsed time is 3.06284 seconds.

FYI this is something I picked up from Pascal Getreuer's "Writing Fast MATLAB Code" which i strongly recommend if working in Octave, as it currently doesn't have many of the code speedups that Matlab has implemented in recent years.

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112679

To repeat a constant a as dictated by the input shape, you can use

f = @(x) repmat(a, size(x));

Example:

>> a = 5;
>> f = @(x) repmat(a,size(x));
>> f([10 20 30; 40 50 60])
ans =
     5     5     5
     5     5     5

Upvotes: 1

Related Questions