From: Stefan on
Hello,

I would like to subtract each element of a from array b.
a=[2 4 5 1 30 4]
b=[12 32 87 56 45 67 13]
Is there a way to solve this problem without using a for-loop?
Thanks

ex: Subtracting 3rd element of a from array b
5 - [12 32 87 56 45 67 13] = [-7 -27 -82 -51 -40 -62 -8]
From: us on
"Stefan " <aidematlab(a)yahoo.ca> wrote in message <i2k8ns$cdf$1(a)fred.mathworks.com>...
> Hello,
>
> I would like to subtract each element of a from array b.
> a=[2 4 5 1 30 4]
> b=[12 32 87 56 45 67 13]
> Is there a way to solve this problem without using a for-loop?
> Thanks
>
> ex: Subtracting 3rd element of a from array b
> 5 - [12 32 87 56 45 67 13] = [-7 -27 -82 -51 -40 -62 -8]

one of the solutions

a=1:5;
b=1:5;
r=a(3)-b
% r = 2 1 0 -1 -2

us
From: Walter Roberson on
Stefan wrote:
> Hello,
>
> I would like to subtract each element of a from array b.
> a=[2 4 5 1 30 4]
> b=[12 32 87 56 45 67 13]
> Is there a way to solve this problem without using a for-loop?
> Thanks
>
> ex: Subtracting 3rd element of a from array b
> 5 - [12 32 87 56 45 67 13] = [-7 -27 -82 -51 -40 -62 -8]

bsxfun(@minus, b, a.')
From: Fangjun Jiang on
"Stefan " <aidematlab(a)yahoo.ca> wrote in message <i2k8ns$cdf$1(a)fred.mathworks.com>...
> Hello,
>
> I would like to subtract each element of a from array b.
> a=[2 4 5 1 30 4]
> b=[12 32 87 56 45 67 13]
> Is there a way to solve this problem without using a for-loop?
> Thanks
>
> ex: Subtracting 3rd element of a from array b
> 5 - [12 32 87 56 45 67 13] = [-7 -27 -82 -51 -40 -62 -8]

>> repmat(a',1,size(b,2))-repmat(b,size(a,2),1)

ans =

-10 -30 -85 -54 -43 -65 -11
-8 -28 -83 -52 -41 -63 -9
-7 -27 -82 -51 -40 -62 -8
-11 -31 -86 -55 -44 -66 -12
18 -2 -57 -26 -15 -37 17
-8 -28 -83 -52 -41 -63 -9
From: us on
"Fangjun Jiang" <f(a)j.com> wrote in message <i2k9mf$f7f$1(a)fred.mathworks.com>...
> "Stefan " <aidematlab(a)yahoo.ca> wrote in message <i2k8ns$cdf$1(a)fred.mathworks.com>...
> > Hello,
> >
> > I would like to subtract each element of a from array b.
> > a=[2 4 5 1 30 4]
> > b=[12 32 87 56 45 67 13]
> > Is there a way to solve this problem without using a for-loop?
> > Thanks
> >
> > ex: Subtracting 3rd element of a from array b
> > 5 - [12 32 87 56 45 67 13] = [-7 -27 -82 -51 -40 -62 -8]
>
> >> repmat(a',1,size(b,2))-repmat(b,size(a,2),1)
>
> ans =
>
> -10 -30 -85 -54 -43 -65 -11
> -8 -28 -83 -52 -41 -63 -9
> -7 -27 -82 -51 -40 -62 -8
> -11 -31 -86 -55 -44 -66 -12
> 18 -2 -57 -26 -15 -37 17
> -8 -28 -83 -52 -41 -63 -9

firstly, i came up with a bad solution because i didn't read the OP carefully enough - sorry...
second, walter's solution using BSXFUN is the way to go...

us