Clear Filters
Clear Filters

Add an array to a cell arrayn within a for loop

1 view (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

Accepted Answer

Stephen23
Stephen23 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]}

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices 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!