|
A(1:2:end,:)=A(1:2:end,:) + repmat(x1,size(A(1:2:end,:),1),1);
A(2:2:end,:)=A(2:2:end,:) + repmat(x2,size(A(2:2:end,:),1),1);
Rentian
"per isakson" <poi3@bim1.kth4.se> wrote in message
news:eef386d.0@webx.raydaftYaTP...
> sgrongst wrote:
>>
>>
>> Hello,
>>
>> I have a matrix A of size m x n. I want to
>> add a vector x1 of size 1 x n to every other row of A starting from
>> m=1. Then I want to add
>> a vector x2 (also of size 1 x n) to every other row of A starting
>> from m=2. I tried the following :
>>
>> A(1:2:end,:) = A(1:2:end,:) + x1;
>> A(2:2:end,:) = A(2:2:end,:) + x2;
>>
>> This does not work. So the alternative is a for loop :
>>
>> for i = 1:2:m
>> A(i,:) = A(i,:) + x1;
>> end;
>> for j=2:2:m
>> A(j,:) = A(j,:) + x2;
>> end;
>>
>> This goes way too slow if A is large. Is ther e a vecorized way of
>> doing the above ?
>>
>> -sgrongst
>
> To add matrices they need to have the same size (exception: adding a
> scalar). Didn't the error message say that? Thus, you need to "blow
> up" the row vectors, x1 and x2, to take the same size as the matrix
> in the expression. That can be done with REPMAT or in this case as in
> the sample below, with is a bit fasater.
>
> /per
>
> function A = cssm( m, n )
>
> A = rand( m, n );
> x1 = rand( 1, n );
> x2 = rand( 1, n );
>
> ix1 = 1:2:m;
> ix2 = 2:2:m;
>
> A( ix1, : ) = A( ix1, : ) + x1( ones(1,length(ix1)), : );
> A( ix2, : ) = A( ix2, : ) + x2( ones(1,length(ix1)), : );
>
> return
|