How to create a matrix from multiples of submatrice?
    5 vues (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
    Timon Viola
 le 11 Juin 2020
  
    
    
    
    
    Modifié(e) : madhan ravi
      
      
 le 11 Juin 2020
            I would like to find a smarter way of building a larger matrix from vectors. The following code works fine:
rv = [1 2 3 4];
alpha =[0.0140;
    0.0100;
    0.0100;
    0.0100];
c = [];
for i = 1:4
    c = [c; diag(alpha).*rv(i)];
end
>> c =
    0.0140         0         0         0
         0    0.0100         0         0
         0         0    0.0100         0
         0         0         0    0.0100
    0.0280         0         0         0
         0    0.0200         0         0
         0         0    0.0200         0
         0         0         0    0.0200
    0.0420         0         0         0
         0    0.0300         0         0
         0         0    0.0300         0
         0         0         0    0.0300
    0.0560         0         0         0
         0    0.0400         0         0
         0         0    0.0400         0
         0         0         0    0.0400
Essentially I build a submatrix from a vector. Then I multiple the diagonal submatrix with each element of a vector. Then I concatenate these vertically.
Is there a computationally more efficient way of doing this?
Thanks!
0 commentaires
Réponse acceptée
  madhan ravi
      
      
 le 11 Juin 2020
        
      Modifié(e) : madhan ravi
      
      
 le 11 Juin 2020
  
      Z = reshape(rv,1,1,[]) .* diag(Alpha);
Wanted = reshape(Z,numel(rv),[]).'
2 commentaires
  Michael Soskind
      
 le 11 Juin 2020
				Even more confusing but with no tansposes and in one line:
repmat(diag(alpha),4,1).*reshape(repmat(rv, 4,4),[],4)
  madhan ravi
      
      
 le 11 Juin 2020
				
      Modifié(e) : madhan ravi
      
      
 le 11 Juin 2020
  
			" and in one line"
Wanted = reshape(reshape(rv,1,1,[]) .* ...
    diag(Alpha),numel(rv),[]).'
"Even more confusing"
Why?
N = 1e6;
tic
for k = 1:N
    Z = reshape(rv,1,1,[]) .* diag(Alpha);
    Wanted = reshape(Z,numel(rv),[]).';
end
% Elapsed time is 4.847994 seconds.
toc
tic
for k = 1:N
    repmat(diag(alpha),4,1) .* reshape(repmat(rv, 4,4),[],4);
end
toc
% Elapsed time is 5.865444 seconds.
Plus de réponses (0)
Voir également
Catégories
				En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


