Finding values in a matrix for a given range

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 Commento

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?

Accedi per commentare.

Risposte (3)

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 Commenti

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))
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.

Accedi per commentare.

Walter Roberson
Walter Roberson il 17 Giu 2011
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.
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
>>

Categorie

Richiesto:

il 17 Giu 2011

Community Treasure Hunt

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

Start Hunting!

Translated by