# Add an array to a cell arrayn within a for loop

3 views (last 30 days)
How can I add vectors to a cell array within a for loop? I have a vector wich I want to split in some intervals acording to the indexes in another vector. But when I run my code, I end up only with the last interval.
So, I have vector C = [321 123 145 908 123 13 1 643 16 134 212 674 121 222 11]; and vector idx = [3 7 11 15] and I want to end up with D = {[145 908 123 13 1];[1 643 16 134 212];[212 674 121 222 11]}; (or something like this, but it corresponds to C(3):C(7); C(7):C(11);C(11):C(15). But, for some reason I only got [212 674 121 222 11].
C = [321 123 145 908 123 13 1 643 16 134 212 674 121 222 11];
dx = [3 7 11 15];
for j = 1:(length(idx)-1)
v = {};
vec = [];
for i = idx(j):idx(j+1)
vec = [vec C(i)];
end
v{j,1} = vec;
end

Stephen Cobeldick on 12 Apr 2021
V = [321,123,145,908,123,13,1,643,16,134,212,674,121,222,11];
X = [3,7,11,15];
F = @(b,e)V(b:e);
C = arrayfun(F,X(1:end-1),X(2:end),'uni',0)
C = 1×3 cell array
{[145 908 123 13 1]} {[1 643 16 134 212]} {[212 674 121 222 11]}
Ana Gabriela Guedes on 12 Apr 2021
Thank you!! It worked