Storing a range as a variable

조회 수: 376 (최근 30일)
Steeven
Steeven 2018년 2월 26일
편집: Stephen23 2018년 2월 26일
Imagine the start and end values of a range being set from user input. They could be:
a=3;
b=10;
To extract this range from an array, I simply do:
x(a:b);
But I'd like to save this range as one variable in itself, so that I can insert the range easily many places and only have to change it in one place such as:
range=a:b;
x(range);
This gives an error. MatLab will not store the a:b in this manner since : is a string and I thus am mixing strings with numbers. I could convert the a and b into a string with num2str, but then that range cannot be inserted into the x variable.
Is there a way to do this or do I have to manually put together the range with x(a:b) every time?
  댓글 수: 2
Adam
Adam 2018년 2월 26일
range = a:b;
is perfectly acceptable syntax. : is an operator here, not a string.
Stephen23
Stephen23 2018년 2월 26일
편집: Stephen23 2018년 2월 26일
"This gives an error."
Not when I try it:
>> a = 3;
>> b = 10;
>> range = a:b
range =
3 4 5 6 7 8 9 10
See also the earlier question:

댓글을 달려면 로그인하십시오.

채택된 답변

Angelo
Angelo 2018년 2월 26일
x=[0.1:0.1:2];
range=[3:10];
x(range)
  댓글 수: 1
Jan
Jan 2018년 2월 26일
See: http://www.mathworks.com/matlabcentral/answers/35676-why-not-use-square-brackets . The additional square brackets waste time only. They are the concatenation operator, but "3:10" is a vector already and nothing is concatenated.
In addition it is worth to consider, that
x(a:b)
is faster than
v = a:b;
x(v)
because in the first case, the index vector a:b is not created explicitly.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2018년 2월 26일
편집: Jan 2018년 2월 26일
What's wrong with
x(a:b)
You really need to store it in one variable?
Range.a = a;
Range.b = b;
x(Range.a : Range.b)
Or:
Range = {a,b};
x(Range{1}:Range{b})
You could write a function also:
GetInterval(x, Range)
function y = GetInterval(x, Range)
y = x(Range{1}:Range{b});
end
But this will be slower and worse to read than the direct and simple:
x(a:b)
Note that Matlab seems to avoid the explicit creation of the index vector a:b to save time in this case, but this is not documented.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by