Putting Consecutive numbers into variables
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
DARLINGTON ETAJE
le 4 Juil 2019
Commenté : Walter Roberson
le 18 Juil 2019
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 commentaire
Stephen23
le 4 Juil 2019
Modifié(e) : Stephen23
le 4 Juil 2019
"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).
Réponse acceptée
Stephen23
le 4 Juil 2019
Modifié(e) : Stephen23
le 4 Juil 2019
>> 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 commentaires
Walter Roberson
le 18 Juil 2019
b and are are dummy parameter names, similar to
function result = F(b, e)
result = A(b, e)
end
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!