How to create a matrix with arbitrary dimensions

Hi,
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.

 채택된 답변

Jos (10584)
Jos (10584) 2019년 2월 20일

0 개 추천

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

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)
try
switch Dims
case 1
Res = zeros(1, Sz);
otherwise
ds = ones(1, Dims);
ds = ds .* Sz;
Res = zeros(ds);
end
catch
Res = [];
end
end
You want a Sz-by-Sz-by- ... -by-Sz array, where Dims specfies the number of Sz's
Res = zeros(repmat(Sz, 1, D))

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Geoff Hayes
Geoff Hayes 2019년 2월 20일

0 개 추천

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

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.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

제품

질문:

2019년 2월 20일

댓글:

2019년 2월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by