matlab - extract elements between two number from a matrix/vector -
for example, have 4x4 matrix
= [1, 2, 3, 4; 2, 1, 4, 3; 1, 2, 4, 3; 4, 1, 2, 3;];
for each row, want extract elements between 1 , 3 (assume matrix has elements between 1 , 3, , 1 comes before 3). example, return cell [{2}, {4}, {2,4}, {2}], or better matrix
b= [0, 1, 0, 0; 0, 0, 0, 1; 0, 1, 0, 1; 0, 1, 0, 0;];
now doing loop each row, find index of 1 , 3, set index between them zero, i.e.,
b = zeros(4,4); = 1 : size(a,1) ind1 = find(a(i,:) ==1); ind2 = find(a(i,:) ==3); b(i, a(i,ind1+1:ind2-1) ) = 1; end
any easier way generate matrix b or cell? suggestion appreciated.
okay, might not easier solution, remove loop, should computationally faster:
the idea instead of trying find numbers between 1 , 3 , set them 1, going find numbers outside 1 , 3 , set 0:
b=zeros(4,4); b(a == 1) = 1; b(a == 3) = 1; c = cumsum(b')'; b(c>=2) =1; b(c< 1) =1; %finally want invert this: b = (b-1)*-1; >> b = 0 1 0 0 0 0 1 0 0 1 1 0 0 0 1 0
========== part applies after second edit ==========
d = a.*b % seems cell indexes after? d = 0 2 0 0 0 0 4 0 0 2 4 0 0 0 2 0 e = zeros(4,4); t = 1:size(a,1) e(t,d(t,d(t,:)>0)) = 1; %this re-applies index numbers , create new index matrix through loop........ %or can use e(t,d(t,~~d(t,:))) = 1 same effect, @dev-il end >> e = 0 1 0 0 0 0 0 1 0 1 0 1 0 1 0 0
this give indexes of elements between 1 , 3 a, can use logical indexes find cell numbers want.
Comments
Post a Comment