在Matlab中有与R的负索引等效吗? [英] Is there an equivalent to R's negative indexing in Matlab?
问题描述
在R
中,如果我们有一个向量和一个索引列表,则可以使用负索引来表达我们想要除这些索引之外的所有元素"的想法.特别是,请考虑以下R
代码:
In R
, if we have a vector and a list of indices, we can express the idea that we want "all elements except these indices" using a negative index. In particular, consider the following R
code:
data = rnorm(100)
indices = sample(1:length(data), length(data)/2)
training_data = data[indices]
test_data = data[-indices]
此代码之后,sampled_data
包含data
中所有元素的索引未包含在indices
中. 在matlab中是否与此等效?
After this code, sampled_data
contains all the elements in data
whose indices are not included in indices
. Is there an equivalent to this in matlab?
我直接尝试使用相同的语法(当然是()
而不是[]
,但这只是给出了错误
I tried directly using the same syntax (of course wtih ()
instead of []
, but it just gave the error
Subscript indices must either be real positive integers or logicals.
推荐答案
Matlab不允许使用负索引.您可以删除元素的方法是:
Matlab does not allow negative indices. What you can do to remove elements is this:
data2 = data;
data2(indices) = []; % remove selected elements
但是在进行机器学习时,我更喜欢使用逻辑索引:
But when doing machine-learning stuff I prefer to use logical indexing:
istest = randn(length(data), 1) < 0; % random logicals: 50% 0's and 50% 1's
istrain = ~istest;
% Now operate on data(istest) and data(istrain).
这篇关于在Matlab中有与R的负索引等效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!