MATLAB already has functionality to do this in the bsxfun function. bsxfun will take two matrices and duplicate singleton dimensions until the matrices are the same size, then perform a binary operation on the two matrices. So, for your example, you would simply do the following:

C = bsxfun(@times,mat,vec);
Answer from MrAzzaman on Stack Overflow
🌐
MathWorks
mathworks.com › symbolic math toolbox › symbolic computations in matlab › operators and elementary operations
times - Symbolic array multiplication - MATLAB
Create a 3-by-3 symbolic Hilbert matrix and a 3-by-3 diagonal matrix. ... Multiply the matrices by using the element-wise multiplication operator .*. This operator multiplies each element of the first matrix by the corresponding element of the second matrix.
🌐
MathWorks
mathworks.com › matlab › mathematics › elementary math › arithmetic operations
times - Multiplication - MATLAB
This MATLAB function multiplies arrays A and B by multiplying corresponding elements.
🌐
MathWorks
mathworks.com › matlab › mathematics › elementary math › arithmetic operations
Array vs. Matrix Operations - MATLAB & Simulink
MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices. Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays.
Top answer
1 of 2
4

MATLAB already has functionality to do this in the bsxfun function. bsxfun will take two matrices and duplicate singleton dimensions until the matrices are the same size, then perform a binary operation on the two matrices. So, for your example, you would simply do the following:

C = bsxfun(@times,mat,vec);
2 of 2
2

Referencing MrAzzaman, bsxfun is the way to go with this. However, judging from your function name, this looks like it's homework, and so let's stick with what you have originally. As such, you need to only write two for loops. You would use the second for loop to index into both the vector and the columns of the matrix at the same time. The outer most for loop would access the rows of the matrix. In addition, you are referencing A and B, which are variables that don't exist in your code. You are also initializing the output matrix C to be 2 x 3 always. You want this to be the same size as mat. I also removed your checking of the length of the vector because you weren't doing anything with the result.

As such:

function C = lab11(mat, vec)
[a, b] = size(mat);
C = zeros(a,b);
for i = 1:a
      for k = 1:b
          C(i,k) = mat(i,k) * vec(k);
      end
  end
end

Take special note at what I did. The outer-most for loop accesses the rows of mat, while the inner-most loop accesses the columns of mat as well as the elements of vec. Bear in mind that the number of columns of mat need to be the same as the number of elements in vec. You should probably check for this in your code.


If you don't like using the bsxfun approach, one alternative is to take the vector vec and make a matrix out of this that is the same size as mat by stacking the vector vec on top of itself for as many times as we have rows in mat. After this, you can do element-by-element multiplication. You can do this stacking by using repmat which repeats a vector or matrices a given number of times in any dimension(s) you want. As such, your function would be simplified to:

function C = lab11(mat, vec)
rows = size(mat, 1);
vec_mat = repmat(vec, rows, 1);
C = mat .* vec_mat;
end

However, I would personally go with the bsxfun route. bsxfun basically does what the repmat paradigm does under the hood. Internally, it ensures that both of your inputs have the same size. If it doesn't, it replicates the smaller array / matrix until it is the same size as the larger array / matrix, then applies an element-by-element operation to the corresponding elements in both variables. bsxfun stands for Binary Singleton EXpansion FUNction, which is a fancy way of saying exactly what I just talked about.

Therefore, your function is further simplified to:

function C = lab11(mat, vec)
C = bsxfun(@times, mat, vec);
end

Good luck!

🌐
TutorialsPoint
tutorialspoint.com › matlab › matlab_matrix_multiplication.htm
MATLAB - Matrix Multiplication
Each element in the (i, j)th position, ... jth column of the second matrix. Matrix multiplication in MATLAB is performed by using the * operator....
🌐
MATLABSolutions
matlabsolutions.com › home › notes › element by element operations in matlab programming
Element-by-Element Operations in MATLAB Programming | MATLAB Dot Operators Explained - Notes
Without the dot (.), MATLAB performs matrix operations, which follow rules of linear algebra instead of element-level math. ... Here, each element of A is multiplied by the corresponding element of B.
🌐
MathWorks
mathworks.com › matlab › mathematics › linear algebra
mtimes - Matrix multiplication - MATLAB
For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox). ... The mtimes operator supports operations directly on tables and timetables without indexing to access their variables when one of the operands is a scalar. All elements in the table or timetable input must have data types that support matrix multiplication...
Find elsewhere
🌐
Dummies
dummies.com › article › technology › programming-web-design › matlab › how-to-employ-matrix-multiplication-in-matlab-146892
How to Employ Matrix Multiplication in MATLAB | dummies
March 26, 2016 - You supply a function nam to perform an element-by-element math operation on two objects. You can use the @times function name, which performs multiplication. The two inputs are a row vector and a column vector.
Author:
🌐
MathWorks
mathworks.com › financial toolbox › get started with financial toolbox
Matrix Algebra Refresher - MATLAB & Simulink
Adding or subtracting a scalar and a matrix is allowed and also operates element-by-element. ... Matrix multiplication does not operate element-by-element. It operates according to the rules of linear algebra. In multiplying matrices, it helps to remember this key rule: the inner dimensions ...
🌐
ScienceDirect
sciencedirect.com › topics › engineering › element-multiplication
Element Multiplication - an overview | ScienceDirect Topics
Write MATLAB commands that compute the value of the vector r as shown below. ... We now discuss several different ways to multiply arrays. You can multiply any vector or matrix by a scalar number. Mathcad multiplies each element in the array by the scalar and returns the results.
🌐
MathWorks
mathworks.com › matlabcentral › answers › 344326-i-want-to-perform-element-wise-matrix-multiplication
I Want to perform element wise matrix multiplication - MATLAB Answers - MATLAB Central
June 12, 2017 - You see you can multiply only same classes. Class of a is uint8, so you need to convert b into the same class. ... https://www.mathworks.com/matlabcentral/answers/344326-i-want-to-perform-element-wise-matrix-multiplication#comment_460933
🌐
MIT
stuff.mit.edu › afs › sipb › project › www › matlab › imatlab › node10.html
Matrix and Element-wise Operations
The inner product is given by x' ... multiply or divide them element by element, or if you want to exponentiate each element of a matrix, place a period before the operator....
🌐
MathWorks
mathworks.com › matlabcentral › answers › 112673-element-wise-multiplication-of-vectors-within-matrices-when-multiplying-matrices
Element wise multiplication of vectors within matrices when multiplying matrices. - MATLAB Answers - MATLAB Central
January 16, 2014 - https://www.mathworks.com/matl... the desired operation is to use a for loop to iterate through the third dimension of M1 and M2 and perform 2-D matrix multiplication at each level....
🌐
MathWorks
mathworks.com › matlab › mathematics › linear algebra
Matrices in the MATLAB Environment - MATLAB & Simulink
The matrix product C = AB is defined when the column dimension of A is equal to the row dimension of B, or when one of them is a scalar. If A is m-by-p and B is p-by-n, their product C is m-by-n. The product can actually be defined using MATLAB for loops, colon notation, and vector dot products:
Top answer
1 of 1
1
There are several ways to multiply each column of a matrix by the corresponding element of the vector. The first is to use the REPMAT function to expand the vector to the same size as the matrix and them perform elementwise multiplication using .* -- however, this will require a large amount of memory. For example: To multiply each column of vector b with the row a: a = [1 2 3]'; b = [1 2; 3 4; 5 6]; x = repmat(a,1,size(b,2)); x.*b % or dot(x,b) If the matrix involved is a square matrix then the vector can be converted to a diagonal matrix and then multiplied as follows: Amat = rand(3,3); b = rand(1,3); c = Amat*diag(b); %or %c = Amat*diag(1./Bvec); The second method is to use a FOR loop. For long vectors prior to MATLAB 6.5 (R13), this may take a significant amount of time; however, making use of the acceleration technology introduced in MATLAB 6.5 (R13), this time is drastically reduced. If you're using MATLAB 6.5 (R13), copy the following code into a function file for an example that does this: function B=DivideColumns(N) % Avoiding creating too large a matrix if nargin<1 || N >2500 N = 500; end tic A = 1./hilb(N); c = 1:N; B = A; % So that we don't overwrite A T1 = toc; tic for i=1:N B(:,i) = B(:,i)/c(i); end T2 = toc; S1 = sprintf('Constructing the %d by %d ... A matrix took %f seconds.', N, N, T1); S2 = sprintf('\nDividing the columns of A ... by elements of c took %f seconds', T2); disp([S1 S2]) For large values of N, you can see that generating A will take much more time than performing the division. Another option is to use a diagonal or sparse diagonal matrix form of your vector. For example, the following code will produce a B that agrees with the B returned by the code above: function B = TimesDiag(N) % Avoiding creating too large a matrix if nargin<1 || N >2500 N = 500; end tic A = 1./hilb(N); c = 1:N; T1 = toc; tic % Replace this with "B = A*spdiag(c(:),0,N,N);" % if N is very large: B = A*diag(c); T2 = toc; S1 = sprintf('Constructing the %d by %d ... A matrix took %f seconds.', N, N, T1); S2 = sprintf('\nDividing the columns of ... A by elements of c took %f seconds', T2); disp([S1 S2])
🌐
MathWorks
mathworks.com › matlabcentral › answers › 1445384-what-s-an-efficient-way-to-do-an-element-wise-multiplication-of-matrices-with-different-sizes-withou
What's an efficient way to do an element-wise multiplication of matrices with different sizes without a permutation or fo... - MATLAB Answers - MATLAB Central
September 2, 2021 - I would like to do an element wise multiplication of each column of B by each column of A. That would be done 181 times for each column in B. The code below accomplishes that by replicating matrix B so that it has dimensions of 255x10x181 and then permutes it to have final dimensions of 255x181x10 and then that matrix is multiplied by A. Matlab automatically takes care of replicating matrix A to account for the third dimension.
🌐
MathWorks
mathworks.com › matlabcentral › answers › 2173842-elementwise-multiplication-of-two-3d-matrices
Elementwise multiplication of two 3D matrices - MATLAB Answers - MATLAB Central
February 10, 2025 - To multiply two 3D matrices element-wise in MATLAB, the appropriate operator is the dot multiplication operator `.*`, not `pagemtimes`. The `pagemtimes` function is designed for matrix multiplication, which requires that the inner dimensions ...