Adding Matrices into main diagonal of Matrix
8 views (last 30 days)
Show older comments
I'm trying to add main diagonal matrices into a defined matrix such as:
clc; clear; close all;
n = 10;
x = linspace(0,1,n);
F = @(x) [x.^2, sin(x), cos(x);
1, 0, 1;
x, cos(x), sin(x)];
A_mat = zeros(n,n);
for i = 1:n
tmp = F(x(i));
A = blkdiag(tmp);
end
A
As we can see, matrix is not a 10x10 matrix with the main diagonal filled with the intended values above. How can I adjust this code to do such?
0 Comments
Accepted Answer
Stephen23
on 21 Mar 2023
Edited: Stephen23
on 21 Mar 2023
"As we can see, matrix is not a 10x10 matrix with the main diagonal filled with the intended values above."
After calling BLKDIAG with 10 3x3 matrices I would expect a 30x30 matrix as the output.
"How can I adjust this code to do such?"
A simpler, much more robust alternative (which also works for any sized input matrices):
N = 10;
F = @(x) [x.^2,sin(x),cos(x);1,0,1;x,cos(x),sin(x)];
C = arrayfun(F,linspace(0,1,N),'uni',0);
M = blkdiag(C{:})
4 Comments
Stephen23
on 28 Mar 2023
"So, is their a particular way of doing manipulation with this array type?"
You can loop over the elements (cells) of a cell array, or you can apply any function that is defined to operate on cell arrays. Perhaps CELLFUN helps you:
C = cellfun(@(m) pi.*m+m, C, 'uni',0)
"Or is it not possible to do so?"
Numeric operations (e.g. arithmetic) are defined for numeric arrays, not for container classes.
More Answers (1)
Cameron
on 21 Mar 2023
Why would your matrix be 10x10 instead of 30x30? This is how I would do it if you haven't already calculated your tmp values ahead of time. I also made the code a bit more robust so you can add different size matrices instead of just 3x3 or any other square matrix.
clc; clear; close all;
n = 10;
x = linspace(0,1,n);
F = @(x) [x.^2, sin(x), cos(x);
1, 0, 1;
x, cos(x), sin(x)];
A_mat = zeros(n*size(F(x(1)),1),n*size(F(x(1)),2));
for i = 1:n
tmp = F(x(i));
rowindx = size(tmp,1)*i-(size(tmp,1)-1):size(tmp,1)*i;
colindx = size(tmp,2)*i-(size(tmp,2)-1):size(tmp,2)*i;
A(rowindx,colindx) = tmp;
end
disp(A)
0 Comments
See Also
Categories
Find more on Matrix Indexing 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!