How to assign array range to variable including the "end"-specifier?

41 views (last 30 days)
I need to assign an array range to a variable (e.g A = B(range), where range=2:40), but with the use of the "end"-specifier, something like:
range = 2:end; A = B(range);
I know that "end" needs information about a certain array to get a value.
My question is: Is it possible to specify "range" in such a way that A = B(range) interprets "range" to be 2:end at runtime?

Answers (2)

Guillaume
Guillaume on 30 Mar 2017
Matlab cannot guess that when you write
range = 2:end;
The end means the end of another array, B in this case. In any case, end is just a shortcut for size(arraybeingindexed, dimensionbeingindexed), or for vectors numel(vectorbeingindexed). So you could simply write:
range = 2:numel(B);
A = B(range);
  2 Comments
Jon Coll Mossige
Jon Coll Mossige on 30 Mar 2017
Hi!
Thanks for a good, understandable answer. I have now edited the question slightly, as the former one was poorly defined. -J
Guillaume
Guillaume on 30 Mar 2017
After your edit, I'm afraid the answer is still it's not possible.
Unless you're willing to change the way you index into B and willing to change the way you create the range. In which case, you could create a function that basically replicates what the |colon operator does:
function values = indexer(indexed, varargin)
%indexed: variable to be indexed
%varargin: variable number of index vectors corresponding to each dimension of indexed, of the form
% [b]: single index
% [a b]: range of indices from a to b
% [a s b]: range of indices from a to b with step s
% in all cases, b can be specified as +Inf to indicates maximum range in the corresponding dimension of indexed
indexes = cell(size(varargin));
for dimension = 1:numel(varargin)
index = varargin{dimension};
if index(end) == Inf
if numel(varargin) == 1 %linear indexing
stop = numel(indexed)
else %subscript indexing
stop = size(indexed, dimension);
end
else
stop = index(end);
end
if numel(index) == 3 %[start step stop]
step = index(2);
else
step = 1;
end
indexes{dimension} = start:step:stop;
end
values = indexed(indexes{:});
end
Which you could use for example as:
B = 1:randi(500)+20;
range = [5 Inf];
C = indexer(B, range);
The way I've written it, it works on any dimension:
B = rand(10, 20, 30);
rangecol = [10 Inf];
C = indexer(B, [1 5], rangecol, [2 2 6]);

Sign in to comment.


Stephen23
Stephen23 on 30 Mar 2017
Edited: Stephen23 on 30 Mar 2017
The simplest solution (why waste your time?):
beg = 2;
B = A(beg:end)

Categories

Find more on Programming in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!