フィルターのクリア

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 Center および File ExchangeShifting 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