Inserting non zero element in diagonal position of a nonzero matrix
3 views (last 30 days)
Show older comments
I m trying to insert Insert set of non zero elements in diagonal position of a nonzero matrix
I now have.
A1= [2 3 4 6 7 8
1 3 4 5 7 8
1 2 4 5 6 8]
A2=[1 5
2 6
3 7]
My desired matrix =
A = [ 1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8]
A is divided into 2blocks, each of size 3x4. The first approaching diagonal elements are extracted and given as A2.
Help me insert A2 into A1 so as to get my desired matrix A.
Accepted Answer
DGM
on 23 Dec 2021
Edited: DGM
on 23 Dec 2021
This isn't that much different than Benjamin's answer now that I look at it, but eh. I guess it's my own spin.
This should work for any A1 array with size integer-divisible by 3
A1 = [2 3 4 6 7 8;
1 3 4 5 7 8;
1 2 4 5 6 8];
A2 = [1 5;
2 6;
3 7]*11;
% use larger versions of the test arrays to demonstrate generality
A1 = repmat(A1,2,2);
A2 = repmat(A2,2,2);
% assumes that size(A1) is integer-divisible by 3 in both dimensions
brow = size(A1,1)/3;
bcol = size(A1,2)/3;
C1 = mat2cell(A1,ones(1,brow)*3,ones(1,bcol)*3);
C2 = mat2cell(A2,ones(1,brow)*3,ones(1,bcol));
diagmask = logical([1 0 0; 0 1 0; 0 0 1; 0 0 0]);
A = cell(size(C1));
for br = 1:brow
for bc = 1:bcol
newblock = zeros(4,3);
newblock(diagmask) = C2{br,bc};
newblock(~diagmask) = C1{br,bc}.';
A{br,bc} = newblock.';
end
end
A = cell2mat(A)
More Answers (2)
_
on 22 Dec 2021
Edited: _
on 22 Dec 2021
If I understand what you are trying to do, here is one way. I got some discrepancies between this code's output A and the A you say should result (in the 2nd row, 7th column and in the 3rd row, 8th column), but I believe it was due to typos in your A. It's also possible I misunderstood the objective. I've added 10 to your A2 in order to better see the elements that have been added in.
A1 = [ ...
2 3 4 6 7 8; ...
1 3 4 5 6 8; ...
1 2 4 5 6 7];
A2 = [ ...
1 5; ...
2 6; ...
3 7]+10;
display(A1);
display(A2);
[m,n] = size(A1);
n = n/2;
A = repmat({zeros(m,n+1)},1,2);
for i = [1 2]
for j = 1:m
A{i}(j,[1:j-1 j+1:end]) = A1(j,(i-1)*n+(1:n));
A{i}(j,j) = A2(j,i);
end
end
A = cat(2,A{:});
display(A);
Image Analyst
on 23 Dec 2021
Your desired matrix doesn't seem to match your verbal description, as @James Tursa pointed out. But anyway, try this. It does what you say and almost gives your desired matrix (which I suspect may be wrong, or else A1 is wrong):
A1= [2 3 4 6 7 8
1 3 4 5 6 8
1 2 4 5 6 7];
A2=[1 5
2 6
3 7];
% According to verbal instructions:
A = [A2(1,1), A1(1,1:3), A2(1,2), A1(1,4:end);
A1(2,1), A2(2,1), A1(2, 2:4), A2(2,2), A1(2,5:end);
A1(3,1:2), A2(3,1), A1(3, 3:5), A2(3,2), A1(3,6:end)]
% It almost matches the desired matrix except for locations (2, 7) and (3, 8).
% My desired matrix =
Adesired = [ 1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8]
0 Comments
See Also
Categories
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!