Expand 1-D array to 2-D matrix using 'ones' function and colon ':'

조회 수: 6 (최근 30일)
Edwin
Edwin 2011년 9월 5일
Example:
matrixA = 6:10;
matrixA = matrixA(ones(1,5), :);
or:
matrixB = (6:10)';
matrixB = matrixB(:, ones(1,5));
My Question:
What's going on here? I just don't get it. Is there any reference on this "exotic" usage? Many thanks for any inputs!

채택된 답변

Daniel Shub
Daniel Shub 2011년 9월 5일
It is not that crazy. It is basically
matrixA = 6:10;
for ii = 1:5
for jj = 1:5
temp(ii, jj) = matrixA(1, jj);
end
end
matrixA = temp;
but lump together into a vectorized version. You can get rid of the inner loop with:
matrixA = 6:10;
for ii = 1:5
temp(ii, :) = matrixA(1, :);
end
matrixA = temp;
and you can finally get rid of all loops with
matrixA = 6:10;
temp = matrixA(ones(1,5), :);
matrixA = temp;

추가 답변 (2개)

Oleg Komarov
Oleg Komarov 2011년 9월 5일
matrixA = matrixA(ones(1,5), :)
select all elements from row one 5 times.
matrixB = matrixB(:, ones(1,5));
select all elements from column one 5 times.

Edwin
Edwin 2011년 9월 6일
Thanks to Daniel and Oleg! I was mostly confused with the role of ones(1,5) here, but came to realize how it works when I read the example below from Matlab's help documents:
B = magic(4)
% Swap the two middle columns:
A = B(:,[1 3 2 4])

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by