Filter löschen
Filter löschen

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

13 Ansichten (letzte 30 Tage)
Luqman Saleem
Luqman Saleem am 4 Mär. 2024
Bearbeitet: Stephen23 am 4 Mär. 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 Kommentare
Dyuman Joshi
Dyuman Joshi am 4 Mär. 2024
"Is the following way a correct way?"
Yes, it is correct.
Stephen23
Stephen23 am 4 Mär. 2024
Bearbeitet: Stephen23 am 4 Mär. 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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Hassaan
Hassaan am 4 Mär. 2024
Bearbeitet: Hassaan am 4 Mär. 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.

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by