Adding Matrices into main diagonal of Matrix
7 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2023-3-21
编辑:Stephen23
2023-3-21
"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 个评论
Stephen23
2023-3-28
"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.
更多回答(1 个)
Cameron
2023-3-21
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!