How to Apply Logical Indexing and Then a Subscript to a Vector in One Line of Code
조회 수: 11 (최근 30일)
이전 댓글 표시
Let's say I have a vector
a=(linspace(1,10,10))';
And a set of logicals to shrink this vector
b=logical(zeros(10,1));
b([1:2, 5:6])=logical(1);
c= a(b);
And d is a subcript(s) that comes from some other vector (e) that is the same size as c
e=rand(size(a(b),1),1);
[~,d]=max(e);
Now I want to create vector f
f=c(d);
However, I would like to avoid this middle step of creating and calling for c due to the size of my vectors. The theoretical b and d vectors are readily available from previous steps. In my head, this looked like the following
f=(a(b))(d);
Unfortunately, that did not work. Any help is much appreciated.
댓글 수: 0
채택된 답변
Sean de Wolski
2015년 3월 20일
MATLAB doesn't support cascaded indexing. You could either split the computation into two lines like you've done (and which I recommend!); or write a function that takes in a(b) and d and does the indexing. Either way, MATLAB has to create the intermediate vector so you're not gaining anything but you would be masking the computation with the latter.
f = foo(a(b), d)
댓글 수: 4
Sean de Wolski
2015년 3월 20일
I think you're data storage scheme here is what's making it difficult, see this:
If you use a standard array, or cell array, you could use those two-three lines in a loop, looping over columns of the array and the total will be about 6 lines long.
Do you have a minimal working example with random vectors and say 2-3 of them?
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!