# Rearrange matrices in a cell array

조회 수: 2 (최근 30일)
vanrapa 2019년 4월 10일
댓글: vanrapa 2019년 4월 12일
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.

댓글을 달려면 로그인하십시오.

### 채택된 답변

Alex Mcaulley 2019년 4월 10일
data = cell(1,10);
data(:) = {deal(rand(4))};
idx = 1;
x = rand(4);
newData = [data(1:idx-1),x,data(idx:end-1)];
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
vanrapa 2019년 4월 11일
Thank you for simplying my code. Works perfectly. thank you.

댓글을 달려면 로그인하십시오.

### 추가 답변 (1개)

Daniel 2019년 4월 10일
편집: Daniel 2019년 4월 10일
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이전 댓글 1개 표시이전 댓글 1개 숨기기
Daniel 2019년 4월 11일
Sorry, you need to use curly braces in my last line of code...
% insert the new matrix
gbsfm{idx,1} = newMatrix;
vanrapa 2019년 4월 12일
I guessed so later and changed the last line,
gbsfm{1,idx} = newMatrix;
It generated desired results. Thanks.

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

R2017a

### Community Treasure Hunt

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

Start Hunting!

Translated by