dpb
Posts:
9,251
Registered:
6/7/07


Re: Extracting particular row of a matrix based on specific condition
Posted:
Jan 2, 2014 2:02 PM


On 1/2/2014 12:00 PM, Bruno Luong wrote: > dpb <none@non.net> wrote in message <la3v66$3rm$1@speranza.aioe.org>... > >> Been puzzling over your last comment, Bruno...couldn't decide what you >> meant by "recomputing it". I guess you're speaking of the logical test >> to select nonzero elements instead of just a direct use of the logical >> addressing vector. > > Yes, (ib > 0) is identical as t, wht throw it away with "~" ?
Because they're _not_ the same...OP wants the order in the order found in A whereas the logical array directly returns the order in B. See the difference for the example case...
>> A = [519 520 521 1000]; >> B = [1000 0.12 0.005 0.1 520 0.13 0.001 0.89 518 0.12 0.002 0.98 600 0.14 0.004 0.90]; >> B(ismember(B(:,1),A),2:end) ans = 0.1200 0.0050 0.1000 0.1300 0.0010 0.8900
Returns the first two rows of B which are the 1st and 2nd entries in A, in order. So the logical array has the first two values T, rest F and those two are the ones returned by matching position.
OTOH,
>> [~,ib]=ismember(A,B(:,1)); >> B(ib(ib>0),2:end) ans = 0.1300 0.0010 0.8900 0.1200 0.0050 0.1000 >>
Returns the same two rows but in obverse order (namely the order in which the locations are found in A as requested). The difference is that ib returns the absolute value of the row in B where the corresponding value from A was found and so is [2 1 0 0] numeric instead of [1 1 0 0] logical. Since it isn't a logical array the need to use the logical test to only return the nonzero elements but do need to use them as indices, not logicals.
>> The problem I see with sort() is that I think in the general case the >> results could be jumbled since the two matrices are given >> independently. AFAICT there's no guarantee the magnitude order would >> be the same as the position order in the B array of an arbitrary >> selection of values in the A vector. Or, at least, that's my >> understanding of the OP's quest... >> > > I don't understand. In my command, sort(ib(t)) returns the indexes in > ascending order. Nothing to do with "magnitude".
You're right there; it's on the ib vector instead of B; my bad there...
It accomplishes same thing as above does but the other does it w/o need for an additional sort() operation...


