Populate cell array with matrix that changes for each entry without a for loop
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Let's say I have a pre-allocated cell array A that is m by n. I want to populate A with 4x4 matrices, but one of the elements of the matrices will change depending on it's position in A. I have stored what I want that element to be in an m by n matrix B.
So for example, I want
A(1,1) = [B(1,1),0,0,0; 0,0,0,0; 0,0,0,0; 0,0,0,0]
and
A(1,2) = [B(1,2),0,0,0; 0,0,0,0; 0,0,0,0; 0,0,0,0]
and so on. I need to do this without for loops, as it is far too slow with them.
I have tried doing things along the lines of
A(:,:) = [B(:,:),0,0,0; 0,0,0,0; 0,0,0,0; 0,0,0,0]
but this gives me the following error:
"Error using horzcat
Dimensions of arrays being concatenated are not consistent."
I believe this is because this type of indexing returns the entire matrix B, where I need it to return each element 1-by-1 corresponding to the element of A it is currently trying to assign. How to I do this?
2 commentaires
Stephen23
le 8 Juil 2021
"I need to do this without for loops, as it is far too slow with them."
I doubt that loops in general are slow for this task. Most likely a well-written loop would be quite efficient, but as you did not show us the code you tried, we have no idea how well written it is. Please upload your code by clicking the paperclip button.
Matthew Crowther
le 8 Juil 2021
Modifié(e) : Matthew Crowther
le 8 Juil 2021
Réponses (1)
Jonas
le 8 Juil 2021
i suggest generating the matrix with the kronecker product and then converting into cell array:
bValues=[1 4 8 2; 3 87 1 4];
template=[1,0,0,0; 0,0,0,0; 0,0,0,0; 0,0,0,0];
asMatrix=kron(bValues,template);
asCell=mat2cell(asMatrix,repelem(4,size(bValues,1)),repelem(4,size(bValues,2)))
0 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing 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!