Reordering columns in a matrix

조회 수: 5 (최근 30일)
Omar Mian
Omar Mian 2011년 12월 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
Jan
Jan 2011년 12월 30일
More efficient than -1*ones:
B = -ones(size(A));
or
B = repmat(-1, size(A));

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

답변 (5개)

the cyclist
the cyclist 2011년 12월 30일
I guess you could do
C = A(:,[2 1 3]).*B(:,[2 1 3]);
But why?

Omar Mian
Omar Mian 2011년 12월 30일
Thanks for the suggestions. I should have been more explicit in my question. I want to do the arithmetic before rearranging because in actual use, the equation will involve more variables than used in the example. I tried the following:
C = (A.*B)(:,[2 1 3])
C = [A.*B](:,[2 1 3])
Neither of these work, but I don't understand why that syntax is inappropriate.
"But why?"
Largely curiosity. I want to know if I can avoid the intermediate step.

the cyclist
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:

Fangjun Jiang
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]}))

Andrei Bobrov
Andrei Bobrov 2011년 12월 30일
circshift(fliplr(A.*B),[0 -1])
  댓글 수: 1
Fangjun Jiang
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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by