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

1 visualización (últimos 30 días)
Angus Wong
Angus Wong el 2 de Feb. de 2020
Editada: Angus Wong el 5 de Feb. de 2020
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.

Respuesta aceptada

Jakob B. Nielsen
Jakob B. Nielsen el 3 de Feb. de 2020
matr(ct1,ct2,:)=[1:(k-1) (k+1):9 0];
Is this what you want?
  3 comentarios
Angus Wong
Angus Wong el 4 de Feb. de 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];
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 el 4 de Feb. de 2020
Editada: Angus Wong el 5 de Feb. de 2020
Din't worry, I figured it out already using permute. I will accept your answer anyway. Thanks for your offer.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by