arr=[ [],[],[] ];
for i=1:3
arr(i)=[i,i+1];
end
Expected output: arr=[[1,2],[2,3],[3,4]];
I am trying to put multiple arrays into a single array and I have tried the above code but it does not work
How can I nest arrays?
arr=[ [],[],[] ];
for i=1:3
arr(i)=[i,i+1];
end
Expected output: arr=[[1,2],[2,3],[3,4]];
I am trying to put multiple arrays into a single array and I have tried the above code but it does not work
How can I nest arrays?
What you are trying is very Pythonic, nesting lists in lists. This doesn't work in MATLAB. You have basically two easy options: a multi-dimensional array, or a cell array with arrays.
arr = zeros(3,2); % initialise empty array
arr_cell = cell(3,1); % initialise cell
for ii = 1:3
arr(ii,:) = [ii, ii+1]; % store output as columns
arr_cell{ii} = [ii, ii+1]; % store cells
end
arr =
1 2
2 3
3 4
celldisp(arr_cell)
arr_cell{1} =
1 2
arr_cell{2} =
2 3
arr_cell{3} =
3 4
Cells can take various sized (or even types of) arguments, whereas a multi-dimensional matrix has to have the same number of columns on each row. This makes a cell array more flexible, but the numerical array is a lot faster and has more numerical functions available to it.
A small side-note, I suggest to not use i
as a variable name in MATLAB, as it's a built-in function.