Oliver Amundsen
Oliver Amundsen

Reputation: 1511

Matlab: Assemble submatrices whose #cols and #rows are stored in a vector

I have two vectors, R and C, which have the number of rows and columns, respectively, of submatrices that I need to assemble in a ones matrix I (40x20). There's 12 submatrices total.

R = [4     2     4     4     2     4];
C = [4    16    16     4];

Moreover, all the elements of each submatrix have its value stored in vector k:

k = [3 2 3 3 2 3 2 1 2 2 1 2 2 1 2 2 1 2 3 2 3 3 2 3 ]; % 24 elements

Thus for instance, submatrix M(1:4,1:4) has 4 rows, and 4 columns and value equal to k(1) = 1.

QUESTION: How can I assemble matrix M with all submatrices?

Any ideas? Thanks!

EDIT:

The matrix M should look like this: enter image description here

and the submatrices:

enter image description here

and the values of k:

enter image description here

Upvotes: 1

Views: 99

Answers (1)

rahnema1
rahnema1

Reputation: 15867

Here is a vectorized solution:

R1 = repelem(1:numel(R), R);
C1 = repelem(1:numel(C), C);
[CC RR] = meshgrid(C1, R1);
idx = sub2ind([numel(R), numel(C)], RR, CC);
result = k(idx);

Instead you can use cell array, fill it with sub matrices and then convert the cell array to a matrix.

carr = cell(numel(R), numel(C));
k1 = reshape(k,numel(R),numel(C));
for ii = 1:numel(R)
    for jj = 1:numel(C)
        carr(ii,jj)=repmat(K1(ii,jj), R(ii), C(jj));
    end
end
result = cell2mat(carr)

Upvotes: 1

Related Questions