You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从矩阵中提取每3列并跳过第4、8等间隔列?

How to Extract Columns by Keeping Every 3 Columns (Dropping 4th, 8th, etc.)

Got it, let's figure out how to solve this column extraction problem. You want to keep every 3 columns in a group and drop the 4th, 8th, 12th, etc.—so basically, we need to exclude any column whose 1-based index is a multiple of 4. Here's how to do this in two common tools for matrix operations:

MATLAB Solution

In MATLAB, we can create a logical index to pick out the columns we want to keep. Here's step-by-step code using your example matrix:

% Your example row matrix A
A = [1 23 34 53 67 45 67 45 12 34 45 56 67 87 98 12 1 2 3 45 56 76 87 56];

% Create a logical array: keep columns where 1-based index isn't divisible by 4
keep_cols = mod(1:size(A,2), 4) ~= 0;

% Extract the desired matrix X
X = A(:, keep_cols);

When you run this, X will exactly match the output you're expecting. The mod function checks each column index, and we keep all columns where the remainder isn't 0 when divided by 4.

Python (NumPy) Solution

If you're using Python with NumPy, the approach is similar—we just need to account for NumPy's 0-based indexing. Here's how:

import numpy as np

# Your example row array (reshape to 2D if you need a proper matrix)
A = np.array([1, 23, 34, 53, 67, 45, 67, 45, 12, 34, 45, 56, 67, 87, 98, 12, 1, 2, 3, 45, 56, 76, 87, 56])

# Create a mask: keep columns where (0-based index + 1) isn't divisible by 4
# For a 2D matrix, use A.shape[1] instead of A.shape[0]
keep_cols = (np.arange(A.shape[0]) + 1) % 4 != 0

# Extract X
X = A[keep_cols]  # For a 2D matrix, use A[:, keep_cols]

Adding 1 to the 0-based index converts it to 1-based, so we can check the same divisibility rule as before.

Quick General Tip

No matter which language you're using, the core idea is the same: identify columns where the 1-based position is a multiple of 4, then exclude those columns. You can adapt this logic to other tools (like R, for example) by generating a list of column indices to exclude and selecting everything else.

内容的提问来源于stack exchange,提问作者Aybars

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:43:51