How to generate number of arrays dynamically?

12 次查看(过去 30 天)
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.

采纳的回答

Adam Danz
Adam Danz 2019-10-4
编辑:Adam Danz 2019-10-4
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 个评论
Adam Danz
Adam Danz 2019-10-4
BTW, if all of your arrays are 1x10 and contain numeric values, I recommend the matrix method.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by