MATLAB Answers


How to create a matrix with arbitrary dimensions

Michael Haitz さんによって質問されました 2019 年 2 月 20 日
最新アクティビティ Jos (10584)
さんによって コメントされました 2019 年 2 月 20 日
I like to create a matrix with arbitrary dimensions.
E.g., I need a function getMatrix(m, s), which returns a m-dimensional matrix with size s, filled with zeros or ones.
Could not working out until today, help is appreciated.

  0 件のコメント

サインイン to comment.

2 件の回答

Jos (10584)
回答者: Jos (10584)
2019 年 2 月 20 日

To create an zero array of an arbitray dimensions between 1 and D with arbitry sizes between 1 and S :
D = 10 ;
S = 6 ;
X = arrayfun(@(x) randi(S), 1:randi(D),'un',0)
M = zeros(X{:})
[size(M) ; [X{:}]]

  2 件のコメント

Michael Haitz 2019 年 2 月 20 日
Thank you, this is what I needed.
Maybe my question was not clear enough, I solved it the following way:
function [Res] = CreateMatrix(Dims, Sz)
switch Dims
case 1
Res = zeros(1, Sz);
ds = ones(1, Dims);
ds = ds .* Sz;
Res = zeros(ds);
Res = [];
Jos (10584)
2019 年 2 月 20 日
You want a Sz-by-Sz-by- ... -by-Sz array, where Dims specfies the number of Sz's
Res = zeros(repmat(Sz, 1, D))

サインイン to comment.

Geoff Hayes
回答者: Geoff Hayes
2019 年 2 月 20 日

Michael - this seems like a homework question so see zeros or ones for how to create a matrix of zeros or ones respectively. And see Declare function name, inputs, and outputs for how to build your function.

  1 件のコメント

Michael Haitz 2019 年 2 月 20 日
Ok, I didnt realize that 'ones' or 'zeros' can be called with arbitrary arrays as parameters.
If I take this in account, the solution is easy.
Thank you.

サインイン to comment.

Translated by