nsy
nsy

Reputation: 249

Minus each value of data

I have sort of data,

A = [2 4 6 8 10]

B = [1 2 3 4 5 6 7 8 9 10]

How to write program that can subtracts each value of A from all values of B.

To better understand,

Take A = 2, subtract from all B = [1 2 3 4 5 6 7 8 9 10],
then take A = 4, subtract from all B = [1 2 3 4 5 6 7 8 9 10]
and so on...

Upvotes: 1

Views: 188

Answers (1)

Jonas
Jonas

Reputation: 74940

If you want to create a new array C that contains, in row i the result of B-A(i), you use bsxfun:

A = [2 4 6 8 10];

B = [1 2 3 4 5 6 7 8 9 10];

C = bsxfun(@minus,B,A') %'# 
C =
    -1     0     1     2     3     4     5     6     7     8
    -3    -2    -1     0     1     2     3     4     5     6
    -5    -4    -3    -2    -1     0     1     2     3     4
    -7    -6    -5    -4    -3    -2    -1     0     1     2
    -9    -8    -7    -6    -5    -4    -3    -2    -1     0

If you want to create a new array C that contains the result of B-A(1)-A(2)-..., you write

C = B-sum(A)

C =
   -29   -28   -27   -26   -25   -24   -23   -22   -21   -20

Upvotes: 5

Related Questions