フィルターのクリア

How to rotate rows of a matrix?

20 ビュー (過去 30 日間)
Dominik Mattioli
Dominik Mattioli 2017 年 2 月 15 日
回答済み: Guillaume 2017 年 2 月 15 日
I have a matrix A where each row of A has only one value of 1 and the rest are some other number.
A = [9 8 7 1; 9 1 8 7; 9 8 1 7; 9 1 8 7; 9 8 7 1; 1 9 8 7]
How can I rotate all of the rows individually such that the 1 value is in the first column of each row in the resultant matrix? How about the second column? I'd like to do this without a for-loop because I am working with large matrices.
%%% Result:
% First column.
B = [1 9 8 7; 1 8 7 9; 1 7 9 8; 1 8 7 9; 1 9 8 7; 1 9 8 7];
% Second column.
C = [7 1 9 8; 9 1 8 7; 8 1 7 9; 9 1 8 7; 7 1 9 8; 7 1 9 8];

採用された回答

Roger Stafford
Roger Stafford 2017 年 2 月 15 日
I think a for-loop is your best bet:
for k = 1:size(A,1)
f = find(A(k,:)==1,1);
A(k,:) = circshift(A(k,:),1-f);
end

その他の回答 (2 件)

Image Analyst
Image Analyst 2017 年 2 月 15 日
Try this:
A = [1 0 0 0; 0 1 0 0; 0 0 1 0; 0 1 0 0; 0 0 0 1; 0 0 1 0];
desiredColumn = 1; % or 2 or whatever
output = zeros(size(A)); % Initialize
output(:, desiredColumn) = 1 % Assign desired column to all ones.
  1 件のコメント
Dominik Mattioli
Dominik Mattioli 2017 年 2 月 15 日
Eek, I edited this just after I posted it, I'm sorry. I forgot to add that the order of each row is important. Do you know how to do that too?

サインインしてコメントする。


Guillaume
Guillaume 2017 年 2 月 15 日
A version without loop. Not sure it'd be faster than Roger's answer:
destcol = 1; %column where the 1 must be located
[c, r] = find(A' == 1);
A(sub2ind(size(A), repmat(r, 1, size(A, 2)), mod((1:size(A, 2)) + c - 1 - destcol, size(A, 2)) + 1))

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by