有人可以解释一下在 MATLAB 中从矩阵中删除元素的示例吗?

发布于 2024-07-14 03:46:50 字数 360 浏览 4 评论 0原文

以下示例出现在 MATLAB 教程中:

X = [16  2 13;
     5  11  8;
     9   7 12;
     4  14  1]

使用单个下标删除单个元素或元素序列,并将剩余元素重新整形为行向量。 所以:

X(2:2:10) = []

结果是:

X = [16 9 2 7 13 12 1]

神秘的是,整个第2行和第4行的前两个元素都被删除了,但是我看不到被删除元素的位置和索引向量2:2之间的对应关系: 10.. 有人可以解释一下吗?

The following example appears in the MATLAB tutorial:

X = [16  2 13;
     5  11  8;
     9   7 12;
     4  14  1]

Using a single subscript deletes a single element, or sequence of elements, and reshapes the remaining elements into a row vector. So:

X(2:2:10) = []

results in:

X = [16 9 2 7 13 12 1]

Mysteriously, the entire 2nd row and the first two elements in the 4th row have been deleted, but I can't see the correspondence between the position of the deleted elements and the index vector 2:2:10. Can someone please explain?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

马蹄踏│碎落叶 2024-07-21 03:46:51

您给出的示例显示了线性索引。 当您有一个多维数组并给它一个标量或向量时,它会沿着每列从上到下、从左到右进行索引。 以下是对每个维度进行索引的示例:

mat = [1 4 7; ...
       2 5 8; ...
       3 6 9];
submat = mat(1:2, 1:2);

submat 将包含矩阵的左上角:[1 4; 2 5]。 这是因为子索引中的第一个 1:2 访问第一个维度(行),第二个 1:2 访问第二个维度(列),从而提取 2-乘-2 平方。 如果您没有为每个维度提供以逗号分隔的索引,而是仅提供一个索引,MATLAB 将会对矩阵进行索引,就好像它是一个大列向量一样:

submat = mat(3, 3);     % "Normal" indexing: extracts element "9"
submat = mat(9);        % Linear indexing: also extracts element "9"
submat = mat([1 5 6]);  % Extracts elements "1", "5", and "6"

请参阅 MATLAB 文档 了解更多详细信息。

The example you gave shows linear indexing. When you have a multidimensional array and you give it a single scalar or vector, it indexes along each column from top to bottom and left to right. Here's an example of indexing into each dimension:

mat = [1 4 7; ...
       2 5 8; ...
       3 6 9];
submat = mat(1:2, 1:2);

submat will contain the top left corner of the matrix: [1 4; 2 5]. This is because the first 1:2 in the subindex accesses the first dimension (rows) and the second 1:2 accesses the second dimension (columns), extracting a 2-by-2 square. If you don't supply an index for each dimension, separated by commas, but instead just one index, MATLAB will index into the matrix as though it were one big column vector:

submat = mat(3, 3);     % "Normal" indexing: extracts element "9"
submat = mat(9);        % Linear indexing: also extracts element "9"
submat = mat([1 5 6]);  % Extracts elements "1", "5", and "6"

See the MATLAB documentation for more detail.

沫尐诺 2024-07-21 03:46:51

这很简单。

它基本上从本例中的第二个元素开始,以 2 为步长到达第十个元素(按列),并删除相应的元素。 其余元素产生行向量。

It's very simple.

It basically starts from the second element in this example and goes upto tenth element (column wise) in steps of 2 and deletes corresponding elements. The remaining elements result in a row vector.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文