Storing the output of a for loop in a cell array

3 Ansichten (letzte 30 Tage)
Morgan Roberts
Morgan Roberts am 8 Jan. 2018
Bearbeitet: Jan am 8 Jan. 2018
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

Antworten (1)

Jan
Jan am 8 Jan. 2018
Bearbeitet: Jan am 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);

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by