Create multiple arrays with different names and specific data

10 vues (au cours des 30 derniers jours)
Niet hier
Niet hier le 12 Mar 2020
Modifié(e) : Stephen23 le 12 Mar 2020
I have written a code that works but I think my code can be simplified with a for loop. The problem is that I do not know how.
Data is an array that consists of 12 times an integer, for example [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]
I want:
  • 12 different arrays with different names
  • the first array has to consist of the first and 13th value (with a step size of 12) [1 13]
  • the second array has to consist of the second and 14th value (with a step size of 12) [2 14]
  • the third array has to consist of the third and 14 value (with a step size of 12) [3 15]
  • the fourth array has to consist of the fourth and 14 value (with a step size of 12)
  2 commentaires
darova
darova le 12 Mar 2020
Don't you want 2D matrix? Only 12 arrays?
Stephen23
Stephen23 le 12 Mar 2020
Modifié(e) : Stephen23 le 12 Mar 2020
" but I think my code can be simplified with a for loop."
Yes, it can be written very efficiently using a loop and indexing.
Or probably even more efficiently by keeping the data together and using reshape.
"The problem is that I do not know how."
Just use indexing into one array. Or reshape.
Do NOT try to dynamically access variable names, unless you want to force yourself into writing slow, complex, obfuscated, buggy code that is hard to debug:

Connectez-vous pour commenter.

Réponse acceptée

Turlough Hughes
Turlough Hughes le 12 Mar 2020
It is possible to do exactly what you asked but that is considered a bad coding practice (explanation here).
Why don't you store the values in a single variable as follows:
D = reshape(Data,Aantalsensoren,[]);
and use the indices in an equivalent manner. So instead of D1, you can write:
>> D(1,:)
ans =
1 13
insead of D2, you can write:
>> D(2,:)
ans =
2 14
  2 commentaires
Stephen23
Stephen23 le 12 Mar 2020
Modifié(e) : Stephen23 le 12 Mar 2020
"...but that is c̶o̶n̶s̶i̶d̶e̶r̶e̶d̶ a bad coding practice"
Niet hier
Niet hier le 12 Mar 2020
Thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by