Rearrange matrices in a cell array
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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 个)
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
2019-4-11
Sorry, you need to use curly braces in my last line of code...
% insert the new matrix
gbsfm{idx,1} = newMatrix;
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!