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

조회 수: 4 (최근 30일)
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);

답변 (1개)

Justin
Justin 2014년 5월 5일
편집: Justin 2014년 5월 5일
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
MRC
MRC 2014년 5월 5일
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);
Justin
Justin 2014년 5월 5일
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?

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

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by