Finding values in a matrix for a given range

조회 수: 7 (최근 30일)
Jannie
Jannie 2011년 6월 17일
Example:
I have a vector k =[1 2 3 4 5 6 7 8 9] and a range = [2 3 4] The values corresponding to the range is given by k=k(range) = 2 3 4
Does anyone know how to code it when k and range is matrices?
  댓글 수: 1
Walter Roberson
Walter Roberson 2011년 6월 17일
Is the question to find the indices within k at which the values in "range" are matched? Or is the question to generalize subscripting to the situation where matrices are involved instead of just vectors?

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

답변 (3개)

Laura Proctor
Laura Proctor 2011년 6월 17일
If your range is always going to be a consecutive range of values, then you can try:
k = 1:9;
r = 2:4;
k = k(k>=min(r) & k<=max(r))
If you want to compare each value of r against each value of k, then this would work:
iVals = logical(zeros(size(k)));
for idx = 1:length(r)
iVals = iVals | k==r(idx)
end
k = k(iVals)
This assumes that r is a vector.
  댓글 수: 2
Walter Roberson
Walter Roberson 2011년 6월 17일
If r is going to be a consecutive increasing range of values, then min(r) and max(r) have predictable locations:
k = k(k>=r(1) & k<=r(end))
Laura Proctor
Laura Proctor 2011년 6월 17일
Jannie - could you clarify? I'm answering the question as if range is the range of numbers that you wish to find in k, whereas it could also be interpreted to be the range of index values.

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


Walter Roberson
Walter Roberson 2011년 6월 17일
What would your range represent when you are using matrices? Would it be row indices, column indices, or indices in to the entire matrix?
For some of the possibilities, k(range) would still work.

Andrei Bobrov
Andrei Bobrov 2011년 6월 17일
example:
>> k = randi(35,7)
k =
6 33 24 2 34 18 23
34 28 27 10 2 16 6
34 34 27 2 16 23 5
17 23 14 4 14 25 18
29 2 23 29 27 27 34
5 30 6 25 28 10 12
15 33 25 12 7 24 21
>> range = randi([1 numel(k)],3)
range =
11 25 48
37 35 27
13 44 7
>> k(range)
ans =
23 4 12
16 7 25
30 6 15
>>

카테고리

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