How to create a matrix of four dimensions in which the fourth dimension is not fixed?jkjsdfhlksdjhf
4 views (last 30 days)
Show older comments
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);
0 Comments
Answers (1)
Justin
on 5 May 2014
Edited: Justin
on 5 May 2014
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 Comments
Justin
on 5 May 2014
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?
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!