how can i multiply blocks of a block matrix by a non block-matrix, block to elements?

6 views (last 30 days)
i want multiply blocks of a block matrix by a non block matrix as size of the block matrix is same under blocks, with size non block matrix under elements. for example :
1 0 1 0 2 0 3 0
0 1 0 1 0 2 0 3
1 0 1 0 2 3 4 0 5 0
* 4 5 = 0 4 0 5
0 1 0 1

Answers (1)

BhaTTa
BhaTTa on 20 Nov 2024 at 9:40
Hey @xosro, I assume that you want to multiply each 2x2 block of A by a corresponding element from B. The element B(i, j) should multiply the block in A located at the same block position. Please refer to below sample code which does the same, please make sure to modify it based on your requirement:
% Block matrix A
A = [1 0 1 0;
0 1 0 1;
1 0 1 0;
0 1 0 1];
% Non-block matrix B
B = [2 3;
4 5];
% Size of the block
blockSize = 2;
% Initialize the result matrix C
C = zeros(size(A));
% Loop over each block in A
for i = 1:blockSize:size(A, 1)
for j = 1:blockSize:size(A, 2)
% Determine the block index
blockRow = (i-1)/blockSize + 1;
blockCol = (j-1)/blockSize + 1;
% Extract the block from A
blockA = A(i:i+blockSize-1, j:j+blockSize-1);
% Multiply the block by the corresponding element in B
C(i:i+blockSize-1, j:j+blockSize-1) = blockA * B(blockRow, blockCol);
end
end
% Display the result
disp('Resulting matrix C:');
disp(C);

Tags

Community Treasure Hunt

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

Start Hunting!