Populate cell array with matrix that changes for each entry without a for loop

5 visualizzazioni (ultimi 30 giorni)
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
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.
Matthew Crowther
Matthew Crowther il 8 Lug 2021
Modificato: Matthew Crowther il 8 Lug 2021
Note that my code is more complicated than the example I gave. The relevant parts are given here:
tic
for j = 1:m
for k = 1:n
A{j,k} = [-R2, LW_space(j,k), 0, 0; -LW_space(j,k) -R2, gamma*B(j,k), 0; 0, -gamma*B(j,k), -R1, -R1*Mz0; 0, 0, 0, 0];
end
end
toc
This is how I would do it using a for loop. The tic toc outputs that this takes 19.785803s on my computer for m = 1001, n = 10000. In reality I will be working with far larger numbers and need to do later calculations on the matrices stored in A. I have attached my .m file for further reference if needed. I am aware that the speed may simply be due to working with large arrays, but I was wondering if it is possible without loops.

Accedi per commentare.

Risposte (1)

Jonas
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)))

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by