Rearrange matrices in a cell array

6 ビュー (過去 30 日間)
vanrapa
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
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 件のコメント
vanrapa
vanrapa 2019 年 4 月 11 日
Thank you for simplying my code. Works perfectly. thank you.

サインインしてコメントする。

その他の回答 (1 件)

Daniel
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 件のコメント
Daniel
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
vanrapa 2019 年 4 月 12 日
I guessed so later and changed the last line,
gbsfm{1,idx} = newMatrix;
It generated desired results. Thanks.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by