How to create a matrix of four dimensions in which the fourth dimension is not fixed?jkjsdfhlksdjhf

Hi, I would like to create a matrix of four dimensions, in which the last dimension is not fixed, in the sense that: suppose
r=3
n=2
m=5
A=[1;2;2;3;1]
I want to create B=zeros(r,n,m,?) in which for each t=1,2,3,4,5 the fourth dimension is indicated by A without using loops, i.e. B is composed by
B(:,:,1,1)=zeros(3,2);
B(:,:,2,1)=zeros(3,2);
B(:,:,2,2)=zeros(3,2);
B(:,:,3,1)=zeros(3,2);
B(:,:,3,2)=zeros(3,2);
B(:,:,4,1)=zeros(3,2);
B(:,:,4,2)=zeros(3,2);
B(:,:,4,3)=zeros(3,2);
B(:,:,5,1)=zeros(3,2);

Respuestas (1)

If you don't need to compile your code Matlab is very flexible with array sizes. For example if you have A = zeros([2 2]); you can then do A(2, 3) = 5; and Matlab will resize the array. You can then remove that extra column by A(2, 3) = [];
It's easier (for me anyways) to think of the operation in terms of a 2D array and then understand that the operation will perform the same way on an ND array.
You could:
B = zeros([r m n A(1)]);
And then if you assign something to
B(r, m , n, A(2)) = val;
Matlab will automatically resize the array. Using those commands you could both grow and shrink your array as needed for each timestep. Does this answer the question?
If you don't want to lose the data from B for each timestep you could make B a cell array of numeric arrays of different sizes such that:
for iter = 1:length(A)
B{i} = zeros([r m n A(i)]);
end
Then at t = 1;
B{1}(1, 1, 2, 1) = val1 + val2;
or whatever you need;

4 comentarios

Thanks but the actual matrices in my code are very big, I need something simpler and without loops.
Can you post any examples of how you want to operate on B and explain further why you want to change the array size? I'm not sure I understand what you need. Also, can you explain further on what you are trying to do. There may be a better way to accomplish it.
If you simply want to reset B to a new array for each t you can:
B = zeros([r m n A(t)]);
I don't want to reset B at each t. B should be a four dimensional matrix
B(:,:,1,1)=zeros(3,2);
B(:,:,2,1)=zeros(3,2);
B(:,:,2,2)=zeros(3,2);
B(:,:,3,1)=zeros(3,2);
B(:,:,3,2)=zeros(3,2);
B(:,:,4,1)=zeros(3,2);
B(:,:,4,2)=zeros(3,2);
B(:,:,4,3)=zeros(3,2);
B(:,:,5,1)=zeros(3,2);
Using
B = zeros([3 2 5 3]);
will create the same size 4D array as your code above.
Do you want to access different values at different t's or actually change the size of the array? I don't think I fully understand your intent. What are you trying to accomplish using this?

Iniciar sesión para comentar.

Categorías

Preguntada:

MRC
el 5 de Mayo de 2014

Editada:

el 26 de Jun. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by