Azzera filtri
Azzera filtri

How to generate number of arrays dynamically?

12 visualizzazioni (ultimi 30 giorni)
I want to generate number of arrays based on user input value. (I assume each array is of fixed dimension e.g. 1 x 10)
prompt = 'How many arrays do you want to generate? ';
N = input(prompt);
% Need a logic that will generate N number of arrays with each of 1x10 size %
Kindly suggest the solution.
Thank you.

Risposta accettata

Adam Danz
Adam Danz il 4 Ott 2019
Modificato: Adam Danz il 4 Ott 2019
The n - arrays can be stored as rows of a matrix or as elements of a cell array.
They can be allocated as NaN, 0s, 1s, logicals, and many other forms. The examples below are allocated as NaNs.
N = 8;
% Generate n-arrays, each 1x10, in a matrix
nArrays = nan(N,10);
% Generate n-arrays, each 1x10, in a cell array
nArrays = arrayfun(@(x){nan(1,10)},1:N)';
Instead of nan() you can use any of the following (plus more!)
  • zeros()
  • ones()
  • false()
  • true()
  • ones() .* x % where x is any value
*Note: If you were expecting 10 independent variables, that's not recommended and should be avoided. See more info on Dynamic Variable Naming and why it should be avoided.
How to access the arrays
% Matrix method:
nArrays = nan(N,10);
% access the 4th array
nArrays(4,:)
% access the 3rd value from each array
nArrays(:,3)
% access the 6th value from the 2nd array
nArrays(2,6)
% Cell array method
nArrays = arrayfun(@(x){nan(1,10)},1:N)';
% access the 4th array
nArrays{4}
% access the 3rd value from each array
cellfun(@(x)x(3),nArrays)
% access the 6th value from the 2nd array
nArrays{2}(6)
More info on matlab indexing
  4 Commenti
Adam Danz
Adam Danz il 4 Ott 2019
BTW, if all of your arrays are 1x10 and contain numeric values, I recommend the matrix method.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by