Make a transpose function in for loop

조회 수: 3 (최근 30일)
Slo
Slo 2011년 11월 30일
I have to make transpose function in for loop for matrix. I am trying to get it to work but it needs some imporvements.
function cd=MyTranspose(A)
[row col] = size(A);
for m=1:length(row)
for n=1:length(col)
cd(n,m)=A(m,n);
end
end

채택된 답변

Walter Roberson
Walter Roberson 2011년 11월 30일
Suggested improvement: do not use a variable name of "cd", as that conflicts with the commonly-used MATLAB routine cd() . Get out of the habit now of using variable names that match common MATLAB routines, before you get stuck calling your variables "sum" and having a heck of a time debugging your program.
Other than the above: You need to be more specific about what you were hoping for from us, keeping in mind that since this is an assignment you are doing, we are likely to avoid giving you anything that might be considered an "answer" to the assignment.
  댓글 수: 3
Andrei Bobrov
Andrei Bobrov 2011년 11월 30일
length(row) -> row
Walter Roberson
Walter Roberson 2011년 11월 30일
Good catch, Andrei. Likewise length(col) should be col.

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

추가 답변 (1개)

Jan
Jan 2011년 11월 30일
It is essential to pre-allocate the output. Otherwise the output matrix grows with every iteration and the runtime increases exponentially with the matrix size.
This method is 10% faster (Matlab 2009a/64/Win7) using the linear index instead of 2 indices:
function B=MyTranspose(A)
[row, col] = size(A);
B = zeros(col, row); % Pre-allocate!
iX = 1;
for iCol = 1:col
iY = iCol;
for iRow = 1:row
B(iY) = A(iX);
iY = iY + col;
iX = iX + 1;
end
end

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by