From: Thethos Hauser on
Hello

I'm looking for a quiker way to do this:

1 1 1 - 1 2 3 = 0 -1 -2
2 2 2 1 0 -1

i.e. to subtract one vector from every line of a matrix (which do have the same number of columns)

right now i'm doing it like this
for ii = 1:number_of_lines
a(ii,:) = b(ii,:) - c;
end

is there any faster way of doing this (as i have quite a lot of subtractions to do...)?

thank you very much
thethos
From: Raul on
Hi,

you could try subtracting the matrix c=repmat([1,2,3],number_of_lines,1) from the matrix containing the lines 111, 222, ...
the repmat command repeats the vector [1,2,3] number_of_linesx1 times

cheers,
Raul

"Thethos Hauser" <maturarbeit(a)gmx.ch> wrote in message <hsdtif$rkh$1(a)fred.mathworks.com>...
> Hello
>
> I'm looking for a quiker way to do this:
>
> 1 1 1 - 1 2 3 = 0 -1 -2
> 2 2 2 1 0 -1
>
> i.e. to subtract one vector from every line of a matrix (which do have the same number of columns)
>
> right now i'm doing it like this
> for ii = 1:number_of_lines
> a(ii,:) = b(ii,:) - c;
> end
>
> is there any faster way of doing this (as i have quite a lot of subtractions to do...)?
>
> thank you very much
> thethos
From: us on
"Thethos Hauser" <maturarbeit(a)gmx.ch> wrote in message <hsdtif$rkh$1(a)fred.mathworks.com>...
> Hello
>
> I'm looking for a quiker way to do this:
>
> 1 1 1 - 1 2 3 = 0 -1 -2
> 2 2 2 1 0 -1
>
> i.e. to subtract one vector from every line of a matrix (which do have the same number of columns)
>
> right now i'm doing it like this
> for ii = 1:number_of_lines
> a(ii,:) = b(ii,:) - c;
> end
>
> is there any faster way of doing this (as i have quite a lot of subtractions to do...)?
>
> thank you very much
> thethos

one of the solutions

m=magic(3);
v=10*ones(1,size(m,2));
r=bsxfun(@minus,m,v)
%{
% r =
-2 -9 -4
-7 -5 -3
-6 -1 -8
%}

us
From: Matt J on
"Thethos Hauser" <maturarbeit(a)gmx.ch> wrote in message <hsdtif$rkh$1(a)fred.mathworks.com>...

> right now i'm doing it like this
> for ii = 1:number_of_lines
> a(ii,:) = b(ii,:) - c;
> end
>
> is there any faster way of doing this (as i have quite a lot of subtractions to do...)?
==============

It depends on the relative magntiudes of number_of_lines and length(c).

If length(c) is only 3 for example and number_of_lines=10000, the fastest way would probably be to do this (even faster than bsxfun)

for jj = 1:3
a(:,jj) = b(:,jj) - c(jj);
end