Rearrange matrices in a cell array
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello,
I am generating some 10 square matrices (4x4), say 1 to 10, using a for loop and storing it in a cell array. And I am also generating another square matrix (4x4), say x, which I would need to move to some position in the cell array depending on user input.
For example, if the user specifies 3, then the matrices should be rearranged such that,
1 then 2 then x then 3 then 4 and so on till 10.
Similarly, if the user specifies 2, then the arrangement would be,
1 then x then 2 then 3 and so on till 10.
It is very important that I reorder the matrix ‘x’ to the specified position, as I would be adding the matrix elements in each position in a particular way.
So how do I go about doing that?
I have written the following code so far,
n = 10 ;
gbsfm = cell(n, 1) ;
for i = 1 : n
a11 = rand(1,1)
a12 = rand(1,1)
a21 = rand(1,1)
a22 = rand(1,1)
A=[a11 a12 0 0; a21 a22 0 0; 0 0 0 0; 0 0 0 0]
gbsfm{i} = A
val = gbsfm{i};
gbsm = sprintf('matrix_%d.mat',i);
save(gbsm,'val');
end
But I have no idea as to how to proceed further. Any pointers would be very helpful.
0 commentaires
Réponse acceptée
Alex Mcaulley
le 10 Avr 2019
data = cell(1,10);
data(:) = {deal(rand(4))};
idx = 1;
x = rand(4);
newData = [data(1:idx-1),x,data(idx:end-1)];
Plus de réponses (1)
Daniel
le 10 Avr 2019
Modifié(e) : Daniel
le 10 Avr 2019
Hi vanrapa,
you would need to expand the existing cell array by one element, shift the existing elements and store the new matrix at the desired index...
Hope this helps...
% this would be the index you want your new matrix to be stored at
idx = 2;
% Expand the cell array by one element and shift the existing
% elements starting from idx
gbsfm(idx+1:end+1,1) = gbsfm(idx:end,1);
% insert the new matrix
gbsfm(idx,1) = newMatrix;
3 commentaires
Daniel
le 11 Avr 2019
Sorry, you need to use curly braces in my last line of code...
% insert the new matrix
gbsfm{idx,1} = newMatrix;
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!