Apply pattern to Matrix Indexes in For Loop

조회 수: 3 (최근 30일)
Olivia Licata
Olivia Licata 2017년 12월 20일
댓글: Star Strider 2017년 12월 23일
Hello, I have a list of values in groups of three. Imagine a column [x1 x2 x3... x112146] I would like to plot x versus y of
(x1,x2) (x2, x1), (x1, x3), (x3,x1), (x2, x3), (x3, x2)
The next group of three would be
(x4, x5), (x5,x4), (x6, x4), (x4, x6), (x5, x6), (x6,x5)
The order within groupings doesn't really matter. I was able to create a pattern for my previous plot with groupings of two by establishing indices and then sorting by even or odd. (code below)
xy = zeros(length(za_twos),2);
xy(:,1)=za_twos(:,1);
for i = 2:(length(za_twos)+1)
if mod(i,2)==0
xy(i-1,2)=za_twos(i,1);
else
xy(i-1,2)=za_twos(i-2,1);
end
end
This returned
(x1, x2) (x2, x1) (x3, x4) (x4, x3)
(in two columns representing x and y)

채택된 답변

Star Strider
Star Strider 2017년 12월 20일
See if this does what you want:
V = (1:18)'; % Original Vector
Vr = reshape(V, 3, []); % Reshape To (3xN) Matrix
idx = nchoosek(1:3,2); % Create Index Permutations - Half
idx = [idx; fliplr(idx)]; % Create Index Permutations - All
hax = axes('NextPlot', 'add');
for k1 = 1:size(Vr,2)
plot(hax, Vr(idx(:,1), k1), Vr(idx(:,2), k1), 'p')
end
I used a linear vector to test the code, so after you run this to be certain if it produces the result you want, substitute your own vector for ‘V’. (The length of your vector is evenly divisible by 3, so my code here should work with your column vector.) I plotted them all on the same axes.
  댓글 수: 2
Olivia Licata
Olivia Licata 2017년 12월 23일
Thank you! This did work, it took a little long since the plotting went stepwise through the loop, but the index permutations were very helpful and I was able to adjust this for groupings 4-10 as well. I changed the plot to a scatter plot and adjusted all the points to one color for personal preferences. Thank you so much!
Star Strider
Star Strider 2017년 12월 23일
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by