Adding Matrices into main diagonal of Matrix
    14 Ansichten (letzte 30 Tage)
  
       Ältere Kommentare anzeigen
    
    Thomas Rodriguez
 am 21 Mär. 2023
  
    
    
    
    
    Kommentiert: Stephen23
      
      
 am 28 Mär. 2023
            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 Kommentare
Akzeptierte Antwort
  Stephen23
      
      
 am 21 Mär. 2023
        
      Bearbeitet: Stephen23
      
      
 am 21 Mär. 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 Kommentare
  Stephen23
      
      
 am 28 Mär. 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.
Weitere Antworten (1)
  Cameron
    
 am 21 Mär. 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 Kommentare
Siehe auch
Kategorien
				Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


