Changing matrix into order pairs
이전 댓글 표시
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
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
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
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.
Alexandra Harkai
2016년 10월 27일
Couldn't agree more.
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
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!