필터 지우기
필터 지우기

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

조회 수: 13 (최근 30일)
Luqman Saleem
Luqman Saleem 2024년 3월 4일
편집: Stephen23 2024년 3월 4일
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
Dyuman Joshi
Dyuman Joshi 2024년 3월 4일
"Is the following way a correct way?"
Yes, it is correct.
Stephen23
Stephen23 2024년 3월 4일
편집: Stephen23 2024년 3월 4일
"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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Hassaan
Hassaan 2024년 3월 4일
편집: Hassaan 2024년 3월 4일
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.

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by