Borrar filtros
Borrar filtros

How to generate number of arrays dynamically?

12 visualizaciones (últimos 30 días)
Ajinkya Bankar
Ajinkya Bankar el 4 de Oct. de 2019
Comentada: Adam Danz el 4 de Oct. de 2019
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.

Respuesta aceptada

Adam Danz
Adam Danz el 4 de Oct. de 2019
Editada: Adam Danz el 4 de Oct. de 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 comentarios
Ajinkya Bankar
Ajinkya Bankar el 4 de Oct. de 2019
Thank you very much.
Adam Danz
Adam Danz el 4 de Oct. de 2019
BTW, if all of your arrays are 1x10 and contain numeric values, I recommend the matrix method.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by