MATLAB Answers

# How to give an array with dynamic size as a paramter to fucntion?

2 views (last 30 days)
Gözde Üstün on 17 May 2020
Commented: Gözde Üstün on 17 May 2020
Hey!
I have a problem. I want to use an array with dynamic size. I mean user can define a size for an array and each element of this array is also an another array:
If user wants an array with a 5 element, the user will wuse the function like that
[A,B,C,D,E]=trying(d)
and each of these A,B,C,D,E will be an array like
A=zeros(d,d,2,d);
B=zeros(d,d,2,d);
C=zeros(d,d,2,d);
D=zeros(d,d,2,d);
E=zeros(d,d,2,d);
or if user wants an array with 2 element, the user can write that:
[A,B]=trying(d)
and the fucntion should do that:
A=zeros(d,d,2,d);
B=zeros(d,d,2,d);
What I mean is that the parameter will be an array with a dynamic size
How can I do that in MATLAB ? I have to use MATLAB and I am very new in MATLAB

#### 0 Comments

Sign in to comment.

### Accepted Answer

Ameer Hamza on 17 May 2020
Also, read here why using variable names like A, B, C, is not recommended: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. Instead use cell arrays.

#### 4 Comments

Show 1 older comment
Ameer Hamza on 17 May 2020
No need to use eval(). Here is a one-liner
function [varargout] = trying(d)
varargout = repmat({zeros(d,d,2,d)}, 1, max(nargout,1));
end
Stephen Cobeldick on 17 May 2020
"I know eval is not a good function ... because in this case eval is the best"
I very much doubt that eval is "the best" for this task.
Ameer Hamza already showed a much better solution using repmat, here are some other much better ways:
function varargout = trying(d)
varargout = cell(1,max(1,nargout));
varargout(:) = {zeros(d,d,2,d)};
end
function varargout = trying(d)
for k = max(1,nargout)):-1:1
varargout{k} = zeros(d,d,2,d);
end
end
Much simpler, neater, and more efficient using basic MATLAB arrays and indexing.
eval is what beginners use to force themselves into writing slow, complex, inefficient code.
Gözde Üstün on 17 May 2020
thanks a lot

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!