How to correctly store and access data in a 4D array?

11 visualizaciones (últimos 30 días)
Luqman Saleem
Luqman Saleem el 4 de Mzo. de 2024
Editada: Stephen23 el 4 de Mzo. de 2024
Suppose I store some 2-by-2 matrices in a 4D array as following
data = zeros(10,5,2,2);
for i = 1:10
for j = 1:5
a = [i+j, 0;
i-j, 0];
data(i,j,:,:) = a;
end
end
later, I want to acess these 2-by-2 matrices. How can I correctly access them? Is the following way a correct way?
i = 2;
j = 5;
matrix = reshape( data(i,j,:,:), 2, 2)
I have tested this method for several i and j. it seems to work, but I am not sure if this always gives correct result.
  2 comentarios
Dyuman Joshi
Dyuman Joshi el 4 de Mzo. de 2024
"Is the following way a correct way?"
Yes, it is correct.
Stephen23
Stephen23 el 4 de Mzo. de 2024
Editada: Stephen23 el 4 de Mzo. de 2024
"Is the following way a correct way?"
It seems to be. If you permute the dimensions of that matrix then you would not need to RESHAPE all the time.
Note: explicit RESHAPE is better than uncontrolled SQUEEZE.

Iniciar sesión para comentar.

Respuesta aceptada

Hassaan
Hassaan el 4 de Mzo. de 2024
Editada: Hassaan el 4 de Mzo. de 2024
It can be and other way could be:
% Initialize a 4D array to store 2-by-2 matrices
data = zeros(10,5,2,2);
% Fill the array with 2-by-2 matrices
for i = 1:10
for j = 1:5
a = [i+j, 0;
i-j, 0];
data(i,j,:,:) = a;
end
end
% Access a specific 2-by-2 matrix without reshape
i = 2;
j = 5;
matrix = squeeze(data(i,j,:,:));
% Display the accessed matrix
disp(matrix);
7 0 -3 0
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
Feel free to contact me.

Más respuestas (0)

Categorías

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

Etiquetas

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by