mxn and nxn matrix element-wise multiplication without for loop

I have 2 2D matrices. First one, A, is mxn where m=n*k and second one, B, is nxn. How do I do element-wise multiplication of every nxn square sub matrix of A with B without for loop? and sum all elements of every multiplied nxn matrix and get a nx1 vector? Below is what I did with for loop. I need to perform the for loop in one row.
n = 10;
k = 5;
A = rand(k*n,n);
B = rand(n,n);
results = zeros(k,1);
for i=1:k
results(i) = sum(B.*A(1+n*(i-1):i*n,:),'all');
end

6 Comments

I don't think your code is doing what you think it is doing. It is taking a single element from A, multiplying all elements of B by it, and then summing all the resulting values.
You are right! I just edited my question. It was just an example I created for the question.
Does using arrayfun() count as "using a for loop" ? These days arrayfun() is implemented internally, but in the older days it was a function like any other function and included MATLAB-level for loops.
Actually as long as it creates the nx1 vector in one line it is fine.
What about the requirement to use elementwise multiplication and not use for loops? What about achieving this all in a single row?
If the solution can provide all of these then it is perfect! If it is not possible to vectorize then one line of solution also acceptable.

Sign in to comment.

 Accepted Answer

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2020b

Asked:

on 26 Oct 2020

Commented:

on 26 Oct 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!