Separate a vector into pairs of segments
Show older comments
Hello to everybody.
I've been learing Matlab for a while and I've been writing a code where I would need to separate a certain row vector, let's say p:
p=[1 2 3 4...n] where n is always a pair number
into n/2 pairs of segments that must be as: p1[1,2], p2[3,4], p3[5 6],...
It would be nice if, choosing the n value, the pairs of segments could be obtained automatically.
Let me thank you in advance for your help.
Vincenzo
Answers (3)
Image Analyst
on 18 Jan 2016
Edited: Image Analyst
on 18 Jan 2016
0 votes
Why do you need them in separate vectors? What's wrong with the original?
But I don't see any point in having a bunch of separately named variables. http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
Star Strider
on 18 Jan 2016
This will do what you want:
p = [1:6];
pMat = reshape(p', 2,[])'
pMat =
1 2
3 4
5 6
PLEASE do not name the rows of what I have assigned as ‘pMat’ individual names such as ‘p1’, ‘p2’, etc. This is extremely poor programming practice. Refer to them instead as ‘pMat(1,:)’, ‘pMat(2,:)’, etc.
Guillaume
on 18 Jan 2016
If you are asking how to create numbered variables p1, p2, p3, etc. then the answer is an emphatic: don't do that! It only leads to problems and has no benefits. I suspect Stephen Cobeldick will be along shortly with a detailed post of all the reasons.
The logical way of holding several 'similar' arrays is to use a cell array. It is very easy to convert a vector into a cell array of pairs using cell2mat:
p = 1 : 14; %for example
assert(mod(numel(p), 2) == 0, 'p doesn't have an even number of elements');
c = mat2cell(p, 1, ones(1, numel(p) / 2) * 2)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!