curiousexplorer
curiousexplorer

Reputation: 1237

Curious behaviour with anonymous functions in Octave and MATLAB

Hi I am curious why I am getting the following behaviour with MATLAB and Octave

octave:7> pdf = @(x) (0<=x && x<1).* (x) + (1<=x && x <=2).* (2-x);  
octave:8> 
octave:8> t = 0:0.1:1;
octave:9> 
octave:9> y = pdf(t)
y =

   0   0   0   0   0   0   0   0   0   0   0

octave:10> 

I get the same behavior with MATLAB i.e. y is a zero vector.

But if I add the following for loop

for i=1:size(t,1) 
  y(i) = pdf(t(i))
end

then I get the correct result.

 Columns 1 through 19:

 0.00000   0.10000   0.20000   0.30000   0.40000   0.50000   0.60000   0.70000   0.80000   0.90000   1.00000   0.90000   0.80000   0.70000   0.60000   0.50000   0.40000   0.30000   0.20000

 Columns 20 and 21:

   0.10000   0.00000

Upvotes: 1

Views: 276

Answers (1)

Pursuit
Pursuit

Reputation: 12345

The && and || are the short circuit operators, meant for use with scalars. Replace with & or |. I get an error when executing the above (vectorized) code in Matlab (R2011B).

After replacing the && with & it seems to work as you expect.

Upvotes: 5

Related Questions