Reordering columns in a matrix
5 次查看(过去 30 天)
显示 更早的评论
Hello,
I want to multiply 2 matrices elemntwise and swap columns 1 and 2 in the result:
A = [1 2 3; 1 2 3; 1 2 3; 1 2 3];
B = -1*ones(size(A));
AB = A.*B;
C = AB(:,[2 1 3]);
I am using 2 steps to do this (lines 3 & 4). How do I do this in a single step (single line of code)?
1 个评论
回答(5 个)
the cyclist
2011-12-30
You cannot index results in that way. See, for example, the accepted answer in this thread about features that are "missing" in MATLAB:
0 个评论
Fangjun Jiang
2011-12-30
If you have to do this, you can use subsref()
a=magic(3)
b=subsref(a,substruct('()', {':',[2,1,3]}))
In your case, it will be
C = subsref(A.*B, substruct('()', {':',[2,1,3]}))
0 个评论
Andrei Bobrov
2011-12-30
circshift(fliplr(A.*B),[0 -1])
1 个评论
Fangjun Jiang
2011-12-31
What a surprise answer, andrei! But I would still go with the subsref() function. After all, it is the function format of the re-arrangement. To challenge you, what if A.*B is a 4x4 or 5x5 matrix but I want to swap the first and second column?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!