3D matrix (I guess is an indexing question?)

1 次查看(过去 30 天)
I have a 9x9x9 matrix (simple). It is created by:
matr=zeros(9,9,9);
for ct=1:9
matr(:,:,ct)=ct;
end
I then type: (step 2, see below)
for ct1=1:9
for ct2=1:9
k=gen;
matr(ct1,ct2,:)=[matr(ct1,ct2,[1:(k-1) (k+1):9]) 0];
end
end
where gen is a function that generates a random integer from 1 to 9, inclusive.
I want my code to be able to:
Step 1: For every 9x9 position, a value of unique k is generated.
Step 2: The value of k is removed in that position in the 3rd dimmention vector. Every numbers after k are shifted forward, and a zero is added on the last element. (e.g. initial matr(2,1,3)=1:9, then matr(2,1,3)=[1:6 8 9 0] if ct1=2, cy2=1 and k=7)
Step 3: The ultimate plan is to run this bloc of code multiple times (less than 6 times, and the value of k will not be repeated).
An example to illistrate what do I mean in step 3:
Let's say ct1=4, ct2=6, k=5. First run results from matr(4,6,3)=1:9 to matr(4,6,3)=[1:4 6:9 0]. This blog of code runs again and k is now 2. So it will give matr(4,6,3)=[1 3:4 6:9 0 0], and so on. However, my code is not able to do this at the moment, I will consider this once step 2 (this problem) is out of the way.
It returns an error (In red: Dimensions of arrays being concatenated are not consistent.), even I changed the line to:
matr(ct1,ct2,:)=[matr(ct1,ct2,[1:(k-1) (k+1):9]);0];
Please help.

采纳的回答

Jakob B. Nielsen
Jakob B. Nielsen 2020-2-3
matr(ct1,ct2,:)=[1:(k-1) (k+1):9 0];
Is this what you want?
  3 个评论
Angus Wong
Angus Wong 2020-2-4
Let me say another example:
I know I can do this:
A=[1 2 3 4 5;6 7 4 9 10];
I want to delete the value 4 in the first row of A and replace it with 0 at the end to keep the size of A unchanged. So I type:
for ct=1:size(A,2)
if A(1,ct)==4
A(1,:)=[A(1,[1:(ct-1) (ct+1:end)]) 0];
end
end
I achieved:
A=[1 2 3 5 0;6 7 4 9 10];
Instead of doing this in a row or column, I want to do this operation in the 3rd dimmention in a 3D matrix.
Angus Wong
Angus Wong 2020-2-4
编辑:Angus Wong 2020-2-5
Din't worry, I figured it out already using permute. I will accept your answer anyway. Thanks for your offer.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by