How to properly input a range in a vector

조회 수: 27 (최근 30일)
Steeven
Steeven 2018년 2월 26일
댓글: Jos (10584) 2018년 2월 26일
I have a code in this style:
range=a:b;
A(range);
The a and b are set with the user's input via a prompt box (with inputdlg). They could be i.e.
a=1;
b=37;
This works fine. But I'd like to be able to not have a range as well; that is, a range that covers all rows. Setting
a=1;
b=end;
does not work. This other answer says that instead of end, the size of the vector should be retrieved:
a=1;
b=numel(A);
The problem with this is that numel isn't variable. I am setting the range outside a loop, while inside the loop the range is used to retrieve the same rows from each looped column (in several datafiles). If no range is set, or if the default is chosen, then all rows should be retrieved. The columns may have different lengths, so I will have to iterate through each column and set a new end-of-range b in each loop. This will cause some delay, so I am searching and asking here to find out if there is a simpler way to simply say "choose all", just like when writing
A(:)
but with the : stored in a variable range.
Thank you.

답변 (2개)

Stephen23
Stephen23 2018년 2월 26일
편집: Stephen23 2018년 2월 26일
The simplest is to use the character ':'
>> A = [1,2,3;4,5,6]
A =
1 2 3
4 5 6
>> range = ':';
>> A(range,1)
ans =
1
4

Jos (10584)
Jos (10584) 2018년 2월 26일
A = magic(4)
range = ':' % in a variable
B = subsref(A,substruct('()',{range, 1}))
But i do think there are easier ways around your problem ... perhaps you can explain more what you really want to accomplish in the end?

카테고리

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