Storing the output of a for loop in a cell array

3 views (last 30 days)
Hi,
I am trying to store the output of a for loop in a cell array -
x = [0,0,0,0,0,5,6,4,3,4,5,6,3,3,5,5,6,3,0,4,4,5,4,4,9,9,0,223,32,4,0,0,0,1];
A = x;
B = zeros(size(x));
n = 1;
B(n+1:end) = A(1:end-n);
branches = cell(zeros());
for i = 1:length(A)
log = abs(A-B) > 5;
no_branches = length(x(log));
end
Whenever the difference between elements in the vector is more than 5 I want to chop the vector and store that as Branch 1, and then continue in Branch 2 until the difference is again more than 5, and then move onto Branch 3, and so on and so forth...
Does anyone have any ideas on this please? I can only seem to get the number of times it happens rather than separate the vector when it does.
Cheers

Answers (1)

Jan
Jan on 8 Jan 2018
Edited: Jan on 8 Jan 2018
Maybe:
x = [0,0,0,0,0,5,6,4,3,4,5,6,3,3,5,5,6,3,0,4,4,5,4,4,9,9,0,223,32,4,0,0,0,1];
Branch = cell(numel(x), 1); % Pre-allocate!!!
ini = 1;
iB = 0;
for ix = 2:numel(x)
if abs(x(ini) - x(ix)) > 5
iB = iB + 1;
Branch{iB} = x(ini:ix - 1);
ini = ix;
end
end
% Care about last chunk:
iB = iB + 1;
Branch{iB} = x(ini:numel(x));
Branch = Branch(1:iB);

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!