ksbiefr
ksbiefr

Reputation: 63

Matrix division with defined Array

i am trying to divide each element of Matrix "A" with each element of "B". I want to make a new matrix of 4 "C"

A=[5    6   9    1; 3    8     9   5; 5    4    2    0;7    8    2    1]
B=[-0.1125,-0.0847,-0.0569,-0.0292]
C =   A ./ B

but i am getting error of

In an assignment A(I) = B, the number of elements in B and I must be the same.

how i fix that issue?

Upvotes: 1

Views: 109

Answers (2)

Nishant
Nishant

Reputation: 2619

try this

C = A./repmat(B,size(A,1),1);

Use @SHAI's answer as it is faster. Here are some stats

n = 100;
k = 100;
A = randi(1000,n,n);
B = randi(1000,1,n);
#mine method
tic;
for i = 1:k
    C = A./repmat(B,size(A,1),1);
end
mine = toc

mine =

    1.2330 seconds

#Shai's method
tic;
for i =1:k
    C = bsxfun(@rdivide, A, B );
end
shai = toc

shai =

    0.1085 seconds

I can give you a more general answer if you would give me general dimensions

Upvotes: 1

Shai
Shai

Reputation: 114786

For this kind of operations it is best using

C = bsxfun(@rdivide, A, B );

Upvotes: 1

Related Questions