Finding values in a matrix for a given range

14 次查看(过去 30 天)
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 中查找有关 Multidimensional Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by