Populate cell array with matrix that changes for each entry without a for loop
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Stephen23
il 8 Lug 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.
Risposte (1)
Jonas
il 8 Lug 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 Commenti
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!