필터 지우기
필터 지우기

How can I compute rms of 3D cubes from 3D meshgrid array in vectorized fashion?

조회 수: 3 (최근 30일)
Lucas
Lucas 2022년 9월 1일
답변: Aman Banthia 2023년 9월 12일
I have a 3D array of magnitude values across x,y,z space - dim: (400,400,300). I want to calculate the rms of the magnitude across all (10,10,10) cubes. My loop solution to this looks as follows:
for iz = 1:30
for iy = 1:40
for ix = 1:40
[idx,idy,idz] = meshgrid([((ix-1)*10)+1:ix*10],[((iy-1)*10)+1:iy*10],[((iz-1)*10)+1:iz*10]);
li = sub2ind(size(magfield),idx,idy,idz);
cmag(ix,iy,iz) = rms(magfield(li),"all");
end
end
end
How could I compute cmag in a vectorized way not using any loops? Thanks!

답변 (1개)

Aman Banthia
Aman Banthia 2023년 9월 12일
Hi Lucas,
I understand that you want to use vectorized method instead of a ‘for’ loop to calculate the rms of the magnitude across all (10,10,10) cubes.
To compute ‘cmag’ in a vectorized way without using any loops, you can utilize the “reshape” and “permute” functions in MATLAB. Here is an example of how you can modify your code:
% Reshape the magnitude array into a 2D array of (10, 10, 10) cubes
reshaped_mag = reshape(magfield, [10, 10, 10, 40, 40, 30]);
% Permute the dimensions to group the cubes together
permuted_mag = permute(reshaped_mag, [1, 4, 2, 5, 3, 6]);
% Compute the RMS along the first three dimensions
cmag = rms(permuted_mag, [1, 2, 3]);
In this vectorized approach, we first reshape the ‘magfield’ array into a 6D array where each cube is represented by the first three dimensions (10, 10, 10). Then, we permute the dimensions to group the cubes together. Finally, we compute the RMS along the first three dimensions using the rms function.
By using this vectorized approach, you can avoid the nested loops and calculate ‘cmag’ efficiently without sacrificing performance.
Please refer to the following MATLAB documentation for more details:
  1. https://in.mathworks.com/help/matlab/ref/rms.html
  2. https://in.mathworks.com/help/matlab/ref/permute.html
  3. https://in.mathworks.com/help/matlab/ref/reshape.html
Hope the above solution helps you.
Best Regards,
Aman Banthia

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by