MATLAB Answers

0

multiply 2 unequal matrices in a loop

Asked by Asha Sharma on 13 Oct 2018 at 22:54
Latest activity Commented on by Asha Sharma on 15 Oct 2018 at 4:15

Q: Multiply each row vector of matrix 'b' , with entire matrix 'a', each time here is my code:

 a=[1 2 3 4;2 0 2 4;0 0 8 2;2 1 3 4]
 b=[3 4 5 1;3 2 3 4]
 % bb = # rows, b
 for bb=1:size(b,1)
      c(bb,:)= b(bb,:).*a;     % the LHS is incorrect- how do I fix it to store this iteration and jump the 4 rows for next iteration..
  end

essentially, the row counter for c needs to jump 4 lines.

  0 Comments

Sign in to comment.

1 Answer

Answer by Bruno Luong on 14 Oct 2018 at 18:27
Edited by Bruno Luong on 14 Oct 2018 at 18:33
 Accepted Answer

I put back my answer (was deleted because you accepted another reply without checking carefully) in case it's what you want:

a=[1 2 3 4;2 0 2 4;0 0 8 2;2 1 3 4]
b=[3 4 5 1;3 2 3 4]
[nr,nc] = size(a);
aa=reshape(a,nr,1,nc);
bb=reshape(b,[1,size(b)]);
c=reshape(aa.*bb,[],nc);

That gives the result:

a =
       1     2     3     4
       2     0     2     4
       0     0     8     2
       2     1     3     4
b =
       3     4     5     1
       3     2     3     4
c =
       3     8    15     4
       6     0    10     4
       0     0    40     2
       6     4    15     4
       3     4     9    16
       6     0     6    16
       0     0    24     8
       6     2     9    16

  6 Comments

i was using those as loop counters. s for matrix a and t for matrix b so s= row 1 of a, gets multiplied into t=1 which is row 1 of b using that formula which is >> Coefficient*a + b

You really need to work on your communication skill, I do the best I can but not sure to understand half of it.

I fix your code as I understand. If t's not right you have to tell what do you expect new to be returned, no need an example bigger than a = 2x2 b = 2x2

a=[3 4 5 1;
    3 2 0 4]
b=[1 2 3 4;
    2 0 2 4;
    0 4 8 2;
    2 1 0 4]
% your way corrected
new = zeros(size(a,1)*size(b,1),size(a,2));
w = 0;
for s= 1:size(a,1)
    for t= 1:size(b,1)
        new(w+t,:)= [(3*a(s,1)+b(t,1)), (5*a(s,2)+b(t,2)), (a(s,3)+b(t,3)), (5*a(s,4)+b(t,4))];
    end
    w=w+size(b,1);
end
new
% my way
coefs = [3 5 1 5];
[nr,nc] = size(b);
bb=reshape(b,nr,1,nc);
aa=reshape(a,[1,size(a)]);
cc = reshape(coefs,1,1,nc);
new2=reshape(cc.*aa+bb,[],nc);
new2

Noted. and thank you! Ran the code it works as I need. I realize that the original questions conveys that for this example I'm expecting a 8X4 matrix, while the updated code to your comment thread indicates I am expecting a 8X1 matrix. Sorry about the confusion. The formula should have indeed continued with , not the + sign. and that results in the 8X4. This really helps as I can use it regardless of the size of the matrix. Thanks again!

Sign in to comment.