Changing matrix into order pairs

10 次查看(过去 30 天)
Ghulam Murtaza
Ghulam Murtaza 2016-10-27
编辑: Amir Afshar 2020-12-18
Hi, I have a matrix A=[1 2;1 3; 2 1;5 6;1 7;6 7],how I can change 'A' like this A=[(1 2);(1 3);(2 1);(5 6);(1 7);(6 7)] or like this A=[[1 2];[1 3];[2 1];[5 6];[1 7];[6 7]]. Thanks in advance

回答(3 个)

Guillaume
Guillaume 2016-10-27
Neither of the two examples you show are remotely valid syntax in matlab since a matrix can only store a single scalar number per element, not matrices. So it's a bit difficult to answer you. Perhaps you want a cell array A = {[1 2];[1 3];[2 1];[5 6];[1 7];[6 7]} since cell arrays allow you to store matrices in each cell. In which case,
A = [1 2; 1 3; 2 1; 5 6; 1 7; 6 7]
newA = num2cell(A, 2)
But the bigger question is why? There's nothing that you can do with the cell array that you couldn't do with the original matrix (and probably more simply).

Alexandra Harkai
Alexandra Harkai 2016-10-27
This gives what you described as [[1 2];[1 3];[2 1];[5 6];[1 7];[6 7]]:
A=[1 2;1 3; 2 1;5 6;1 7;6 7];
B = mat2cell(A, ones(1,6),2);
But, it is not exactly clear what you mean by 'order pairs' or what you mean by [(1 2);(1 3);(2 1);(5 6);(1 7);(6 7)]. What is it you exactly want to do with these 'pairs'? For example, if you just want to access the n-th pair at a time, you can instead simply write
A(n,:)
  2 个评论
Guillaume
Guillaume 2016-10-27
If you're going to use mat2cell to convert all the rows into a cell array (instead of the simpler num2cell), at least don't hardcode the sizes:
B = mat2cell(A, ones(1, size(A, 1)), size(A, 2));
so that it works with A of any size.
Like you, I suspect we've got a case of XY problem where the real question is yet to be asked.

请先登录,再进行评论。


Amir Afshar
Amir Afshar 2020-12-18
编辑:Amir Afshar 2020-12-18
I think what you want is to have each entry in a vector be a pair of elements. To do that, you need to store each pair in a cell:
B = cell(numel(A,1),1);
for i = 1:length(A)
B(i) = {A(i,:)};
end
Then if
A = [1 2; 1 3; 2 1; 5 6; 1 7; 6 7];
Using the above snip of code:
B = 1×3 cell array
{1×2 double} {1×2 double} {1×2 double}
To access a specific element in B, though, you need to use {}.
B{1} returns [1,2]. B{1,2} still gives [1,2], so in order to get the second element from the first pair, you need to do something clever, like (using the dot product with a unit basis vector to extract the second element):
B{1}*[0;1]
This returns 2. As another example, B{4} returns [5,6], but B{4}*[1;0] gives 5:
B{4}*[1;0]
ans =
5

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by