Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to R's negative indexing in Matlab?

Tags:

r

matlab

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]

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.
like image 939
merlin2011 Avatar asked Dec 10 '13 22:12

merlin2011


People also ask

Does Matlab have negative indexing?

Assume its need to use the i variable as -5 to 4 and have to access the corresponding index of input buffer. But in matlab we can't handle negative indexes in matrix or arrays.

Does R have negative indexing?

Negative indexing Unlike in some other programming languages, when you use negative numbers for indexing in R, it doesn't mean to index backward from the end. Instead, it means to drop the element at that index, counting the usual way, from the beginning.

Is negative indexing possible in array?

We can access the elements of an array by going through their indexes. But no programming language allows us to use a negative index value such as -4. Python programming language supports negative indexing of arrays, something which is not available in arrays in most other programming languages.


2 Answers

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).
like image 64
jez Avatar answered Nov 14 '22 23:11

jez


I ended up converting the index array into logicals (rather than generating the logical array directly), because I still wanted the original indexes for other purposes.

indices = datasample(1:length(data), length(data) / 2);
logical = false(length(data) ,1);
logical(indices) = true;
training_data = data(logical)
test_data = data(~logical)

This way of generating logical arrays makes it easier to control the percentage of training vs test examples, at least for me.

However, I still find jez's solution highly educational.

like image 28
merlin2011 Avatar answered Nov 14 '22 23:11

merlin2011