Storing the output of a for loop in a cell array

조회 수: 3 (최근 30일)
Morgan Roberts
Morgan Roberts 2018년 1월 8일
편집: Jan 2018년 1월 8일
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
  댓글 수: 1
Jan
Jan 2018년 1월 8일
What exactly is "the difference between elements"?

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
Jan 2018년 1월 8일
편집: Jan 2018년 1월 8일
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);

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by