フィルターのクリア

How to generate number of arrays dynamically?

12 ビュー (過去 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 Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by