How to vectorize a for loop of matrix division?

I tried to learn the vectorization from the matlab website https://es.mathworks.com/help/matlab/matlab_prog/vectorization.html
And I try to implement this vectorization in my FEM code. Here is a simple code to illustrate my idea:
If we have 10 stiffness matrix k(2-by-2) and nodal force vector f(2-by-1). We try to collect them in K (2-by-2-by-10) and F(2-by-1-by-10)
for i = 1: 10
K(:,:,i)=[i i+1; i-1 i+2];
F(:,i) = [i+1;i+2];
end
% We could use the for loop to solve it. But I hope to boost up the calculation by vectorization
% For loop version
for i = 1: 10
U(:,i) = F(:,i)\K(:,:,i);
end
% for vectorized version ?
U1 = F\K;
Thanks for your help!!!

Answers (1)

Instead of creating 2 x 2 x 10, you can blkdiag() the entries into a 20 x 20 matrix, and likewise blkdiag F into a 20 x 10 matrix. After that, you can use \ between the matrices.
However... in situations where you have reason to believe that your matrices are numerically stable, then
syms A [2 2]
syms b [2 1]
sol = A\b
sol = 
You can now take those formulas and vectorize them, such as
top = (A(1,2,:) .* b(2,1,:) - A(2,2,:) .* b(1,1,:)) ./ (A(1,1,:) .* A(2,2,:) - A(1,2,:) .* A(2,1,:));

2 Comments

Thanks a lot for your detailed answer! However, this example with dimension 2-by-2 is just an illustration. For my interested question, the dimension would be quite large like a 1000-by-1000 matrices division. In this case, how should I vectorize the matrix division?
Thanks for your response again!
You could create a sparse diagonal matrix; https://www.mathworks.com/help/matlab/ref/spdiags.html and then the sparse \ could be used.
However... I suspect that looping would be faster.

Sign in to comment.

Categories

Asked:

on 14 Dec 2021

Commented:

on 15 Dec 2021

Community Treasure Hunt

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

Start Hunting!