I have a vector:
a = [0 0 0 1 1 0 0 0 1 0 0 0 0 1 0 0 1 0 1 0 0 1 0 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0];
I'd like to organize this vector into a matrix with the following criteria: every time I see a 1 I want to copy that 1 and 2 other members before it into a new line, so my resulting matrix will look like this:
b = [0 0 1
0 1 1
0 0 1
0 0 1
0 0 1
1 0 1
0 0 1
0 0 1
1 0 1
0 0 1
0 0 1];
Right now I do it using a for loop:
spikeIndeces = find(a == 1);
for i=1:length(spikeIndeces)
b(i,:) = a(spikeIndeces(i)-2:spikeIndeces(i));
end
I'd like to do this without a loop, in as little lines as possible and as fast as possible.
Thanks in advance!
Kian
% pad a margin for safety
apad=[0 0 a]
i1 = find(apad==1);
idx=bsxfun(@plus,[-2:0]',i1)
b=reshape(apad(idx(:)),3,[])'
% Bruno
apad=[0 0 a]
i1 = find(apad==1);
b=apad(bsxfun(@plus,i1(:),(-2:0)))
% Bruno
i1 = find(apad==1);
b=apad(i1(:)+(-2:0))
% Bruno
Also, I don't know how to use your FEX submission. Do I just download and add it to my path?
Is it possible to achieve this without using any extra functions to make sure that it works on every machine without having to install additional functions?
Thanks!
Kian
"Bruno Luong" <b.l...@fogale.findmycountry> wrote in message <gtil7d$bv4$1...@fred.mathworks.com>...
I have R2006b installed.
Kian,
bsxfun is Matlab builtin function existing from 2007A.
For previous Matlab version, you might use REPMAT to accomplish the same task:
apad=[0 0 a]
i1 = find(apad==1);
b=apad(repmat(i1(:),1,3)+repmat(-2:0,numel(i1),1))
% Bruno