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

5 ビュー (過去 30 日間)
MRC
MRC 2014 年 5 月 5 日
編集済み: Randy Souza 2014 年 6 月 26 日
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 Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by