Putting Consecutive numbers into variables

조회 수: 1 (최근 30일)
DARLINGTON ETAJE
DARLINGTON ETAJE 2019년 7월 4일
댓글: Walter Roberson 2019년 7월 18일
I data in this format a=[1;2;3;7;0;6;7;8;9;2;4;3;14;15;16;17;0;9;2];
what I need to accomplish is to put consecutive numbers into different variables...
in this case the expected outcome is a1=[1;2;3]; a2=[6;7;8;9]; a3=[14;15;16;17]; How do I
  댓글 수: 1
Stephen23
Stephen23 2019년 7월 4일
편집: Stephen23 2019년 7월 4일
"what I need to accomplish is to put consecutive numbers into different variables... "
Do NOT do this. Dynamically accessing variable names is one way that beginners force thmeselves into writing slow, complex, obfuscated, buggy code that is hard to debug:
Your code will be simpler and much more efficient if you simply use one container variable (e.g. a cell array, as my answer shows).

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

채택된 답변

Stephen23
Stephen23 2019년 7월 4일
편집: Stephen23 2019년 7월 4일
>> A = [1;2;3;7;0;6;7;8;9;2;4;3;14;15;16;17;0;9;2];
>> D = diff([false;diff(A(:))==1;false]);
>> F = @(b,e)A(b:e);
>> C = arrayfun(F,find(D>0),find(D<0),'UniformOutput',false);
>> C{:}
ans =
1
2
3
ans =
6
7
8
9
ans =
14
15
16
17
You can access the data in the cell array C using basic indexing:
  댓글 수: 3
DARLINGTON ETAJE
DARLINGTON ETAJE 2019년 7월 18일
F = @(b,e)A(b:e);
Please explain what b and e mean
are they variables...I don't know how to use them for a new dataset
Walter Roberson
Walter Roberson 2019년 7월 18일
b and are are dummy parameter names, similar to
function result = F(b, e)
result = A(b, e)
end

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by