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.
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With