Filter löschen
Filter löschen

Rearrange matrices in a cell array

6 Ansichten (letzte 30 Tage)
vanrapa
vanrapa am 10 Apr. 2019
Kommentiert: vanrapa am 12 Apr. 2019
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.

Akzeptierte Antwort

Alex Mcaulley
Alex Mcaulley am 10 Apr. 2019
data = cell(1,10);
data(:) = {deal(rand(4))};
idx = 1;
x = rand(4);
newData = [data(1:idx-1),x,data(idx:end-1)];
  1 Kommentar
vanrapa
vanrapa am 11 Apr. 2019
Thank you for simplying my code. Works perfectly. thank you.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Daniel
Daniel am 10 Apr. 2019
Bearbeitet: Daniel am 10 Apr. 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 Kommentare
Daniel
Daniel am 11 Apr. 2019
Sorry, you need to use curly braces in my last line of code...
% insert the new matrix
gbsfm{idx,1} = newMatrix;
vanrapa
vanrapa am 12 Apr. 2019
I guessed so later and changed the last line,
gbsfm{1,idx} = newMatrix;
It generated desired results. Thanks.

Melden Sie sich an, um zu kommentieren.

Produkte


Version

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by