MATLAB Answers

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

2 views (last 30 days)
I have a 9x9x9 matrix (simple). It is created by:
for ct=1:9
I then type: (step 2, see below)
for ct1=1:9
for ct2=1:9
matr(ct1,ct2,:)=[matr(ct1,ct2,[1:(k-1) (k+1):9]) 0];
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.


Sign in to comment.

Accepted Answer

Jakob B. Nielsen
Jakob B. Nielsen on 3 Feb 2020
matr(ct1,ct2,:)=[1:(k-1) (k+1):9 0];
Is this what you want?


Angus Wong
Angus Wong on 4 Feb 2020
Sorry, but I am not thinking of that.
Let's say:
Run the first time (say k=3), I will get:
matr(ct1,ct2,:)=[1:2 4:10 0];
Run the second time (say k=6), I will get:
matr(ct1,ct2,:)=[1:2 4:5 7:10 0 0];
Run the third time (say k=10), I will get:
matr(ct1,ct2,:)=[1:2 4:5 7:9 0 0 0];
Yes, your code works if the code only run once, but I want to know how can I index the third dimmention, like I typed in the question.
Angus Wong
Angus Wong on 4 Feb 2020
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];
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 on 4 Feb 2020
Din't worry, I figured it out already using permute. I will accept your answer anyway. Thanks for your offer.

Sign in to comment.

More Answers (0)

Sign in to answer this question.


Translated by