Adding Matrices into main diagonal of Matrix
15 ビュー (過去 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!