A= [1 2 3 4
2 3 4 5
4 5 6 7
.
....]
where each of the rows is stored in a separate vector as such
a1 = [1 2 3 4]
a2 = [2 3 4 5]
.
.
.
an = [1 2 3 4]
and I need to create new cells, using a loop, containing all previous row vectors as follows:
vectors = {a1, a2, a3, ......,an}
in the workspace I get vectors
as a 1 x n
cell and in each cell containing its own vector; e.g. the first cell contains vector a1
, the second cell contains vector a2
, etc. I don't want to copy the code every time I have a different number of vectors, so I'd like to automate this.
You'll want to not hand-copy each row into a separate variable before doing this. The proper way using your desired for
loop would be thus
A = rand(15,39);
vectors = cell(1,size(A,1)); % initialise output
for ii = 1:size(A,1) % loop over all rows
vectors{1,ii} = A(ii,:); % store each row in the cell
end
To do this without a loop (thanks to @beaker)
B = mat2cell(A, ones(1,size(A,1)), size(A,2)).';
though a matrix (so your original A
) would be the best overall, since MATLAB works best with matrices.