So I have the following matrices:
A = [1 2 3; 4 5 6];
B = [0.5 2 3];
I\'m writing a function in MATLAB that will allow me to multiply a vec
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!