필터 지우기
필터 지우기

How to generate number of arrays dynamically?

조회 수: 13 (최근 30일)
Ajinkya Bankar
Ajinkya Bankar 2019년 10월 4일
댓글: Adam Danz 2019년 10월 4일
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
Ajinkya Bankar
Ajinkya Bankar 2019년 10월 4일
Thank you very much.
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