Wednesday, March 11, 2009

Operations element by element

I was wrong, this post will talk about matrices and vectors (yet).

Let's talk about operations element by element.

For example, we have two matrices of same size and we need to multiply and to divide each element:

X = [x11 x12 x13;
x21 x22 x23;
x31 x32 x33].

Y = [y11 y12 y13;
y21 y22 y23;
y31 y32 y33].

Z1 = [x11*y11 x12*y12 x13*y13;
x21*y21 x22*y22 x23*y23;
x31*y31 x32*y32 x33*y33].

Z2 = [x11/y11 x12/y12 x13/y13;
x21/y21 x22/y22 x23/y23;
x31/y31 x32/y32 x33/y33].

The math doesn't have a operation for it, but it's possible using Scilab.

-->X = zeros(3,3);

-->X(:) = [1:9]'
X =

1. 4. 7.
2. 5. 8.
3. 6. 9.

-->Y = ones(3,3) + X'
Y =

2. 3. 4.
5. 6. 7.
8. 9. 10.

-->Z1 = X.*Y
Z1 =

2. 12. 28.
10. 30. 56.
24. 54. 90.

-->Z1 = X./Y
Z1 =

0.5 1.3333333 1.75
0.4 0.8333333 1.1428571
0.375 0.6666667 0.9


The operations sum and subtraction work element by element, like in matrices sum and subtraction.


Logic operations

If we need to use logic operations then we can use the operators:

  • & - AND;
  • | - OR;
  • ~ - NOT.

-->X = rand(3,3) > 0.2
X =

F T T
T F T
T T T

-->Y = rand(3,3,'normal') > 0.5
Y =

T T F
T F T
F F F

-->Z1 = X & Y
Z1 =

F T F
T F T
F F F

-->Z2 = X | Y
Z2 =

T T T
T F T
T T T

-->Z3 = ~X
Z3 =

T F F
F T F
F F F

-->Z4 = (~X) | Y
Z4 =

T T F
T T T
F F F

That's all, I'm thinking about the next subject that I'll talk here. I accept suggestions.

No comments: