Afshin Oroojlooy
Afshin Oroojlooy

Reputation: 1434

Creating Dynamic matrices in MATLAB

I have a problem with defining some matrices in MATLAB. I get three numbers x,y,z as an input from user, then I want to create y-1 empty matrices. For example consider x = 3, y = 4, and z = 2. The required y-1 matrices M1, M2, and M3 are:

size(M1) = [3,4] ~ [x,y]

size(M2) = [4,4] ~ [y,y]

size(M3) = [4,2] ~ [y,z]

The parameters x,y are not known before running the program. If y was 5, the matrices were:

size(M1) = [3,5] ~ [x,y]

size(M2) = [5,5] ~ [y,y]

size(M3) = [5,5] ~ [y,y]

size(M4) = [5,2] ~ [y,z]

Indeed the main problem is that the number of matrices is an input. Please guide me on how I can create a function loop to define this matrices.

Upvotes: 1

Views: 1233

Answers (3)

Stewie Griffin
Stewie Griffin

Reputation: 14939

You could do this without using cells, but I strongly advice you not to, so: One way to do this, with each matrix being part of a cell:

dims = str2num(input('Type in selected x,y,z: ', 's'));

M = arrayfun(@(n) zeros(dims(n), dims(2)), [1 2*ones(1,y-1) 3], 'UniformOutput', 0)

%% In the command window:
Type in selected x,y,z: 3 4 2

M = 
    [3x4 double]    [4x4 double]    [2x4 double]

Note that with the str2num(input()) approach, you can input both: [4 3 2], [4, 3, 2], 4 3 2, 4, 3, 2 or even 4;3;2. It's basically impossible to make mistakes here!

The way this works is: arrayfun performs an operation for each elements of the vector [1 2*ones(1,y-1) 3]. The operation is to create a matrix of zeros, with the desired dimensions. UniformOutput is a parameter that must be set to false, or 0 if the output is something other than scalars.

To access, and make changes to any of the matrices:

When you type M{x}, you can think of that as the equivalent of just a matrix name, i.e. it's fine to use () to index the matrix, straight after the {}.

So, you can do:

M{1}(3,3) = 2;

which would assign the value 2 to the element (3,3) in matrix 1.

Upvotes: 4

Ali Ahmadvand
Ali Ahmadvand

Reputation: 155

X = input('Enter X please: '); 
Y = input('Enter Y please: '); 
Z = input('Enter Z please: '); 
Cells={}
Cells{1}=zeros(X,Y);
for i=2:Y-1
 Cells{i}=zeros(Y,Y);   
end;
Cells{Y-1}=zeros(Y,Z);

Upvotes: 4

Adriaan
Adriaan

Reputation: 18177

M1 = zeros(x,y);
M2 = zeros(y,y);
M3 = zeors(z,y);

Simple enough. Though why M2 and M3 in your question are the same I haven't figured out yet.

Upvotes: 0

Related Questions