How can I find the coordinates of a known vector, within a larger vector?
4 次查看(过去 30 天)
显示 更早的评论
I'd like to take a group of linear vectors, and find where a smaller known vector is placed within them.
For example if I have:
Vector1 = 3 2 4 1 3 2 4 1 3 2 4 2 4 3 4 3 1 4 2 2 3 4 1 4 2
Vector2 = 1 4 2 3 1 4 2 4 2 3 4 3 1 4 2 2 4 1 3 2 4 1 2 3 1 1 1
Vector3 = 1 4 2 3 4 1 4 2 3 1 4 3 4 3 1 4 2 1 4 2 3 1 4 1 3
Vector4 = 1 3 2 4 2 4 1 4 3 2 3 4 3 1 4 2 1 1 3 2 4 2 4 1 2 3
Vector5 = 1 3 2 4 2 1 1 1 3 4 3 2 3 4 3 1 4 2 1 1 3 2 4 2 4 1 2 3
ConstantVector = 3 4 3 1 4 2
I know that each of the vectors 1-5 have the ConstantVector in them somewhere. I would like to be able to quickly output the position of the vector in each case.
The end aim is to be able to put Vectors 1-5 into a matrix of zeros such the sections denoted by ConstantVector are all aligned in columns. For example the above vectors would become:
3 2 4 1 3 2 4 1 3 2 4 2 4|3 4 3 1 4 2|2 3 4 1 4 2 0 0 0 0 0 0
0 0 0 0 1 4 2 3 1 4 2 4 2|3 4 3 1 4 2|2 4 1 3 2 4 1 2 3 1 1 1
ConstantOverLaying = 0 0 1 4 2 3 4 1 4 2 3 1 4|3 4 3 1 4 2|1 4 2 3 1 4 1 3 0 0 0 0
0 0 0 1 3 2 4 2 4 1 4 3 2|3 4 3 1 4 2|1 1 3 2 4 2 4 1 2 3 0 0
0 1 3 2 4 2 1 1 1 3 4 3 2|3 4 3 1 4 2|1 1 3 2 4 2 4 1 2 3 0 0
I've put lines on either side of the ConstantVector just to show that they overlap.
My current thinking is that once I have the coordinates I can use them to automatically shift them left or right as needed when adding them to the matrix of zeroes. If anyone can think of any better ways to do this it is of course welcome.
0 个评论
采纳的回答
Michael Haderlein
2015-2-2
You can use strfind:
Vector1 = [3 2 4 1 3 2 4 1 3 2 4 2 4 3 4 3 1 4 2 2 3 4 1 4 2];
Vector2 = [1 4 2 3 1 4 2 4 2 3 4 3 1 4 2 2 4 1 3 2 4 1 2 3 1 1 1];
Vector3 = [1 4 2 3 4 1 4 2 3 1 4 3 4 3 1 4 2 1 4 2 3 1 4 1 3];
Vector4 = [1 3 2 4 2 4 1 4 3 2 3 4 3 1 4 2 1 1 3 2 4 2 4 1 2 3];
Vector5 = [1 3 2 4 2 1 1 1 3 4 3 2 3 4 3 1 4 2 1 1 3 2 4 2 4 1 2 3];
ConstantVector = [3 4 3 1 4 2];
strfind(Vector1,ConstantVector)
if you want all the vectors 1...5 together:
V={Vector1;Vector2;Vector3;Vector4;Vector5};
cellfun(@(x) strfind(x, ConstantVector),V)
Are you able to do the rest on your own? If you need further help, just ask here.
6 个评论
Michael Haderlein
2015-2-3
You've been close to the solution:
FrameStart = max(Positions)
FrameShift = FrameStart-Positions
MaxLength=max(FrameShift+Lengths)
Empty=zeros(length(V),MaxLength);
for cnt=1:length(V)
Empty(cnt,1+FrameShift(cnt):FrameShift(cnt)+Lengths(cnt))=V{cnt};
end
Instead of an arbitrary starting point, I choose the one goes most left. That simplifies further code. The FrameShift must be defined the other way around - big numbers must be shifted far to the right. Finally, it's just simple replacing.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!