如何对31×6×2×3的4D数组按指定维度计算行列重复中位数?
Hey there! Let's solve this problem efficiently using MATLAB. I'll walk you through both a targeted approach for each shock and a more streamlined one that handles both shocks at once.
Step 1: Understand Your Array Dimensions
Your 4D array df = randn(31,6,2,3) maps to:
- 31 rows (i)
- 6 variables/columns (j)
- 2 shock types (k)
- 3 repetitions (n)
Step 2: Streamlined Solution (Handle Both Shocks at Once)
Instead of processing each shock separately, you can use MATLAB's median function with a dimension argument to compute medians across the repetition dimension (4th dimension) for all shocks in one go:
% Generate your test array (add rng for reproducibility) rng(42); df = randn(31,6,2,3); % Compute median across the 4th dimension (repetitions) median_results = median(df, 4);
The result median_results will be a 31×6×2 array:
median_results(:,:,1): Medians for the first shock (31 rows × 6 columns, each value is the median of 3 repetitions for that row/column)median_results(:,:,2): Medians for the second shock (same structure)
Step 3: Separate Processing (If You Prefer)
If you want to handle each shock individually (like your initial approach), here's how to do it:
% Process first shock eg1 = squeeze(df(:,:,1,:)); % 31×6×3 array median_eg1 = median(eg1, 3); % 31×6 array (median across repetitions, 3rd dimension) % Process second shock eg2 = squeeze(df(:,:,2,:)); % 31×6×3 array median_eg2 = median(eg2, 3); % 31×6 array % Optional: Combine results into a single 3D array median_results = cat(3, median_eg1, median_eg2);
How It Works
- The
median(A, dim)function computes the median values along the specified dimensiondim. For your case, we target the repetition dimension (4th for the full array, 3rd for the squeezed single-shock arrays). squeezeremoves singleton dimensions (here, the shock dimension which is fixed to 1 or 2), simplifying the array to 3D before computing medians.
内容的提问来源于stack exchange,提问作者Rollo99
相关产品推荐
相关产品推荐

