How can I increase the size of matrices in cell arrays with each iteration of a loop?
Show older comments
I have a cell array that is 10x10 with each cell containing a 1x3 matrix of numerical values. This cell array is generated inside a loop that has 10 iterations, thus there are 10 versions of this cell array, each with different values.
I would like to know how to store each iteration of this cell array in a single cell array which is still 10x10, however with each cell containing a 10x3 matrix. Basically, I want each iteration of the loop to add a row to the matrix in each cell and populate those rows with the corresponding cells of the new cell array generated during that iteration.
Accepted Answer
More Answers (2)
There are a few different ways to create such as cell array. If to get it done in a loop:
rng(1) % To replicate at any time and obtain the same results of random numbers
for ii = 1:10
for k=1:10
H{ii,k} = randi([-5,5],1, 3);
end
end
H{1,1}
H{1,2}
H{3,1}
% etc
Fifteen12
on 7 Feb 2023
This code gives two solutions, one that can be implemented after your original iteration (it just harvests the values and puts them into a new matrix), and one that can be implemented during your original iteration (which you'll have to splice into your own code).
% Generate original cell arrays
n = 10;
for k = 1:n
for i = 1:n
for j = 1:n
foo{i, j} = [i, j, k]; %Random values
end
end
original{k} = foo;
end
% Post adaptation from original iteration
for i = 1:n
for j = 1:n
temp = zeros(n, 3);
for k = 1:length(original)
temp(k, :) = original{k}{i, j};
end
out1{i, j} = temp;
end
end
% Adaption during original iteration
out2 = cell(n, n);
for k = 1:n
for i = 1:n
for j = 1:n
out2{i, j}(k, :) = [i, j, k]; %Random values
end
end
end
1 Comment
Jacob Martire
on 7 Feb 2023
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!