Effacer les filtres
Effacer les filtres

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

13 vues (au cours des 30 derniers jours)
Luqman Saleem
Luqman Saleem le 4 Mar 2024
Modifié(e) : Stephen23 le 4 Mar 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 commentaires
Dyuman Joshi
Dyuman Joshi le 4 Mar 2024
"Is the following way a correct way?"
Yes, it is correct.
Stephen23
Stephen23 le 4 Mar 2024
Modifié(e) : Stephen23 le 4 Mar 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.

Connectez-vous pour commenter.

Réponses (1)

Hassaan
Hassaan le 4 Mar 2024
Modifié(e) : Hassaan le 4 Mar 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.

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Tags

Produits


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by