placement of elements from a matrix into another matrix
1 view (last 30 days)
Show older comments
Rupsana Chowdhury
on 24 Apr 2019
Edited: Andrei Bobrov
on 24 Apr 2019
Hi,
I have A matrix like below.
tot_row=5;
tot_col=10;
left_col_begin = tot_col/2;
right_col_begin = left_col_begin + 1;
new_col=3;
left_col_end = (left_col_begin - new_col)+1;
right_col_end = (right_col_begin + new_col)-1;
new_row=3;
A=nan(tot_row,tot_col);
And I have B matrix like below:
B=[10 5
6 4
3 2
8 0
1 3
7 5];
Now I want to get C matrix from A and B such that
B(i,1) for all i= 1:size(B,1)
will be placed on A matrix based on their frequency given in B(i,2)
But for each row rr in A matrix where rr in 1:new_row --
That means for above A matrix, the placement of B(i,1) will be B(i,2) number of times in the following place sequence
A(1,6) -> A(1,5) -> A(1,7) -> A(1,4) -> A(1,8) -> A(1,3)
A(2,6) -> A(2,5) -> A(2,7) -> A(2,4) -> A(2,8) -> A(2,3)
A(3,6) -> A(3,5) -> A(3,7) -> A(3,4) -> A(3,8) -> A(3,3)
My output matrix C is given below. I want this C matrix from A and B based on above placement criteria.
C=
[NaN NaN 6 10 10 10 10 10 NaN NaN
NaN NaN 1 3 6 6 6 3 NaN NaN
NaN NaN 7 7 1 1 7 7 NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];
7 should have 5 times in C matrix as it's frequency is 5 in B matrix, but it is here available for 4 times. Because I don’t have any other spaces (in that 3*6 block) to put 7. So this is fine. My goal is to place as much as I can. If there are any extra space available in that block after all the placements from B matrix, then it will be keep as NaN as like rest of the elements.
Can someone please help me on this? I hope I made my question clear. Please let me know if you have any questions.
Thanks
0 Comments
Accepted Answer
Andrei Bobrov
on 24 Apr 2019
Edited: Andrei Bobrov
on 24 Apr 2019
%{
block of code by Rupsana - initial and final submatrix values and initial
matrix A:
%}
tot_row=5;
tot_col=10;
left_col_begin = tot_col/2;
right_col_begin = left_col_begin + 1;
new_col=3;
left_col_end = (left_col_begin - new_col) + 1;
right_col_end = (right_col_begin + new_col) - 1;
new_row=3;
A=nan(tot_row,tot_col);
% ii - sequence of columns in submatrix
ii = reshape(...
[right_col_begin : sign(right_col_end - right_col_begin) : right_col_end
left_col_begin : sign(left_col_end - left_col_begin) : left_col_end] ,[],1);
[y,x] = ndgrid(1:new_row,ii);
% adjustment of the number of elements for the submatrix
k = cumsum(B(:,2),'reverse');
d = mod(k(1),numel(ii)*new_row);
jj = find(k-d > 0,1,'last');
B(jj,2) = B(jj,2) - d;
B(jj+1:end,2) = 0;
% submatrix insertion into matrix "A"
A(reshape(sub2ind([tot_row,tot_col],y,x)',[],1)) = repelem(B(:,1),B(:,2));
0 Comments
More Answers (0)
See Also
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!