0
votes

I am totally new to Matlab and have a simple question (not that simple for me):

I have a matrix x:

x = 1 2 3 
    4 5 6 
    7 8 9
    10 11 12

and a Vector y:

y = 1 2 3

Now I would like to multiply the numbers 1 to 4 by the first element of the Vector, the numbers 5 to 8 by the second element and 9 to 12 by the last element.

Can´t find a solution. Any help is highly appreciated!

Thanks Paul

1

1 Answers

2
votes

If you modify your input x to set up all "groups" as columns of a new input, let's say xx, e.g. by transposing and reshaping x accordingly, you can use (element-wise) multiplication. MATLAB's implicit expansion allows such (element-wise) matrix operations. (Before MATLAB R2016b, one would need bsxfun for that.)

That would be my solution:

% Inputs
x = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
y = [1 2 3]

% Transpose and reshape x to set up all "groups" as new columns
xx = reshape(x.', 4, 3)

% (Element-wise) Multiplication using implicit expansion
z = xx .* y

Output:

x =
    1    2    3
    4    5    6
    7    8    9
   10   11   12

y =
   1   2   3

xx =
    1    5    9
    2    6   10
    3    7   11
    4    8   12

z =
    1   10   27
    2   12   30
    3   14   33
    4   16   36

Hope that helps!