Matlab:提取矩阵的第N个元素,同时保持矩阵的原始顺序 [英] Matlab: Extracting Nth element of a matrix, while maintaining the original order of matrix

查看:692
本文介绍了Matlab:提取矩阵的第N个元素,同时保持矩阵的原始顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立一些代码以提取矩阵的某些元素,并按照提取顺序将这些值仅保留在另一个矩阵中.

I am attempting to set up some code to extract certain elements of a matrix, and keeping only these values in another matrix, in the order they were extracted.

示例:如果我有一个随机的1X20矩阵,但只希望从4和5开始的每Nth = 5个元素,我希望它构造一个仅由4、5、9、10, 14、15、19、20.

Example: If I have a random 1X20 matrix, but want only every Nth = 5th element beginning with 4 and 5, I would want it to construct a new matrix (1x8) consisting only of 4, 5, 9, 10, 14, 15, 19, 20.

到目前为止,我有:

r = rand(1,20);
n = 5;
a = r(4 : n : end);
b = r(5 : n : end);

因此,我不是要两个单独的矩阵,而是要按其原始时间顺序排列一个矩阵(同样,一个由4、5、9、10、14、15、19、20顺序的元素组成的1x8矩阵) .本质上,我希望能够对任意数量的值执行此操作,同时仍保持元素所在的原始顺序.

So instead of two separate matrices, I instead want one matrix in its original chronological order (again, a 1x8 matrix consisting of the elements in the order of 4,5,9,10,14,15,19,20). Essentially, I'd like to be able to do this for any number of values while still maintaining the original order the elements were in.

推荐答案

为以45开头的索引创建所有索引以分别索引到r中,然后对其进行排序以保持元素的顺序为它最初在r中.

Create all the indices to index into r separately for indices starting with 4 and 5 and then sort them to keep the order of elements as it was originally in r.

所以,这应该工作-

ab = r(sort([4:n:numel(r) 5:n:numel(r)]))

这篇关于Matlab:提取矩阵的第N个元素,同时保持矩阵的原始顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆