Filling matrix with cell arrays in a loop leaves all rows empty except the last one
4 views (last 30 days)
Show older comments
Hi,
I was wondering if someone would be able to explain what is causing data to be lost from my matrix (except the last row) when I run it through a loop? My problem is much like this person's:
However, I already created the cell array outside the loop using matrix = cell(48,1); and am still getting this issue. I'm not doing anything with the matrix in the loop except this:
matrix(i) = {[Var1 Var2 Var3]};
I'm assuming there's an issue with my syntax in this line of code, but I can't seem to find a solution to this anywhere.
Thanks in advance!
1 Comment
VBBV
on 4 May 2023
However, I already created the cell array outside the loop using matrix = cell(48,1); and am still getting this issue.
Thats unlikely to have any issue, The problem in the link that you sent, is that of declaration of cell array inside the loop,
% declared outside the loop as in your case
dataBase=cell(3,3);
for n=1:3
t = randi([0 10],1,1);
while (t<3 || t>6)
t = randi([3 6],1,1);
end
alpha = ([0:pi/t:2.*pi]);
si = sin(alpha);
co = cos(alpha);
M =[rad2deg(alpha); si ; co]';
x=M(:,1)';
ys=M(:,2)';
yc=M(:,3)';
dataBase{n,1}=x;
dataBase{n,2}=ys;
dataBase{n,3}=yc;
end
dataBase
Answers (1)
VBBV
on 4 May 2023
Edited: VBBV
on 4 May 2023
% place this line outside of all loops
matrix = cell(48,1);
matrix{i} = [Var1 Var2 Var3];
4 Comments
VBBV
on 4 May 2023
ok, did you do something like this ?
% declared outside the loop as in your case
dataBase=cell(3,3);
n = 1:3;
for i = n
t = randi([0 10],1,1);
while (t<3 || t>6)
t = randi([3 6],1,1);
end
alpha = ([0:pi/t:2.*pi]);
si = sin(alpha);
co = cos(alpha);
M =[rad2deg(alpha); si ; co]';
x=M(:,1)';
ys=M(:,2)';
yc=M(:,3)';
dataBase(i) = {[x ys yc]};
end
dataBase
See Also
Categories
Find more on Loops and Conditional Statements 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!