3
function y = dd2(x1,x2)
y=0;
if x1==0 && x2==0
  y=1;
end

This would not work because the input cannot be an array. I hope to make it can work for an array X of 1*m, and an array Y of 1*n so when you dd2(X,Y) it creates a m*n matrix with 1 at the position where X=0, Y=0 and zero otherwise

Is there any function that does this has already been implemented in matlab? (like a 2D discrete delta function) I didn't find it.. The dirac(x) would return inf which I want is zero. Is there a way to change the inf to 1? Thanks

diodeBucks
  • 173
  • 3
  • 11

1 Answers1

2

There is a magical function called bsxfun that does almost everything in MATLAB and certainly finds another perfect setup here. The implementation with it would look something like this -

y = bsxfun(@and,x1(:)==0,x2(:).'==0)

Sample run with x1 as 1x4 and x2 as 1x6 -

x1 =
     0    -1    -1     0
x2 =
    -1    -1    -1    -1     0     0
y =
     0     0     0     0     1     1
     0     0     0     0     0     0
     0     0     0     0     0     0
     0     0     0     0     1     1

Look at the positions of 0's in x1, x2 and 1's in the output y to verify the results.


General Case Solution

For a general case, you can define an anonymous function like so -

func1 = @(x1,x2) x1==0 & x2==0

Then, use it within bsxfun for the deseired output -

y = bsxfun(func1,x1(:),x2(:).')

Thus, with every new conditional statement, you only need to change func1! As an example, you can add one more conditional statement in it -

func1 = @(x1,x2) x1==0 & x2==0 | x1 <0
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • That really helps! It's probably better to change `x1(:)==0,x2(:).'==0` to `x1(:).'==0,x2(:)==0` by x and y order convention. A follow-up question: if I have multiple functions in the same folder, how can I specify @and is referring to my dd2() function? – diodeBucks Mar 01 '15 at 17:16